imports in __init__.py

Ben Finney ben+python at benfinney.id.au
Thu Dec 17 23:34:57 EST 2009


Phil <phily05 at gmail.com> writes:

> I use distutils / setup.py to install 'packagename', where...
> /packagename
>     __init__.py
>     modulename.py
>
> modulename.py has a class named 'classname'.

As per PEP 8, it's best if user-defined classes are named with
TitleCase, so ‘ClassName’.

> From an arbitrary python module, I 'import packagename'.

At that point, you have all the names that were defined within
‘packagename’, available inside the namespace ‘packagename’. Since
‘modulename’ is a module in that package, the module's namespace is
available to you via ‘packagename.modulename’.

> In said module, I want to use the 'classname' class from
> 'packagename.modulename', by doing 'packagename.classname(params)'.

The name ‘ClassName’ is not in the namespace ‘packagename’. It is in the
namespace ‘packagename.modulename’, so you'll need to access it there::

    import packagename.modulename
    packagename.modulename.ClassName(params)

You can import the class from that namespace explicitly::

    from packagename.modulename import ClassName
    ClassName(params)

or you can import the module from the package namespace::

    from packagename import modulename
    modulename.ClassName(params)

> I have seen this done by having either 'import modulename' and/or
> 'from modulename import *' in 'packagename's __init__.py.

Importing the module in the package would mean you would not have to
import the module yourself when using the package; it would not change
the qualification necessary of the namespace.

Importing using the ‘from foo import *’ form is usually a bad idea,
since it clobbers namespaces and makes it impossible to tell by looking
at the import code where the name ‘ClassName’ appeared from. Best to
import only explicit names, as above.

If you want to abbreviate, you can use the ability to rename while
importing::

    import packagename.modulename as foo
    foo.ClassName(params)

which keeps the names explicit and traceable.

-- 
 \       “Give a man a fish, and you'll feed him for a day; give him a |
  `\    religion, and he'll starve to death while praying for a fish.” |
_o__)                                                       —Anonymous |
Ben Finney



More information about the Python-list mailing list