Python Imports Convention

I noticed that in Python code it is usually preferred to explicitly import parts of the module you need, for example

from django.core.urlresolvers import reverse
from django.db import models

      

However, I noticed that this is not like the standard Python library modules where I usually see, for example:

import os
import sys

something = os.path.join('home', 'ludo')
other = sys.argv('dunno')

      

instead

from os.path import join
from sys import argv

something = join('home', 'ludo')
other = argv('dunno')

      

Is there any rationale or documented convention for this?

+3


source to share


3 answers


the sacred leadership style is pretty loose on this point:

When importing a class from a module containing the class, it is usually well written:

from myclass import MyClass
from foo.bar.yourclass import YourClass

      

If this spelling causes local name conflicts, then write them down

import myclass
import foo.bar.yourclass

      

and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".

There are actually no "rules" for this, namely some of the pointers mentioned above. If you are not hindered, for example, the name conflicts, you can do whatever you see fit.



However, as mentioned in the link, you should keep in mind that

Wildcard imports (from * imports) should be avoided as they are unclear what names are present in the namespace, confusing both readers and many automated tools.

+7


source


In response to Tim Castellins' answer, this is also an acceptable alternative:

from my_module import models as my_models
from their_module import models as their_models

class MyOtherModel(their_models.Foo):
    ...

class MyThirdModel(my_models.Bar):
    ...

      

That is, you are allowed to assign alternative names to imported modules. You have to consider readability, however, so make sure it stays open which module is being referenced.

As an example, when inferring classes from another model, you can do this:



# in myproject.views
from shop.views.cart import CartDetails as ShopCartDetails

class CartDetails(ShopCartDetails):
    # my overridden methods
    ...

      

This gives you the ability to refer to the same class name when importing into urls.py

:

# in myprojects.urls
from myproject.views import CartDetails

    ...
    url(r'^cart/$', CartDetails.as_view(), name='cart'),
    ...

      

+1


source


Most people will use the PEP8 style guide: https://www.python.org/dev/peps/pep-0008/#imports

0


source







All Articles