Efficiency/style issues of import <module> vs. from <module> import <name>, ...

Stephen Hansen me+list/python at ixokai.io
Thu Jun 17 12:33:19 EDT 2010


On 6/17/10 9:12 AM, python at bdurham.com wrote:
> Are there any efficiency or style guidelines regarding the choice
> of "import <module>" vs. "from <module> import <name>, ..."?

There are no legitimate efficiency issues. In theory, module.blah is
slightly slower then blah, but that "slightly" is largely irrelevant in
globals. If you need to do module.blah a lot in a loop, you want to
re-bind it into a local anyways before that loop if performance starts
mattering that much.

Style wise, the only guideline is, "from <module> import *" is often
(but not always) bad. It pollutes the namespace, making it difficult to
know exactly what's defined and where it is defined. Multiple "import
*"'s are especially bad.

Explicitly importing certain names is perfectly fine. Its clear and
explicit. Someone seeing, "MyRandomClass" can search in the code and
they'll find that import and know precisely where to go to look for it.

> If one only needs to import a few names from a module, are there
> specific benefits to explictly importing these names?

Clarity, sometimes. There is no general rule here though. It depends on
the structure and layout. Its a case-by-case situation; is it more clear
to your natural reading to have 'module.MyRandomThing' or just
'MyRandomThing' in your code?

An example: let's say you have a "handlers" module containing certain...
uh.. handlers.. you have defined for your application.

You could either:

    import handlers

Or:

    from handlers import MyHTTPHandler, MySMTPHandler, MyNNTPHandler

In this case, I'd consider it possible that in code usage, its entirely
sufficient to call "MyHTTPHandler" and have it be clear and
understandable for future non-you coders. "handlers.MyHTTPHandler" is
slightly more explicit, but due to the naming and structure of this
specific code, redundant as well. That may not always hold true.

Now, this is all IMHO: the style guide does not define any 'guidelines'
on this, except that its okay to use "from ... import ..." to pull in
classes and (implicitly) constants, and despite how the rules say 'one
module per line' its OK to pull in more then one name -from- a module at
once.

> My understanding is that both forms of the import command require
> the entire module to be processed.

Yes.

"from <module> import <name>" is just a shortcut for:

import <module>
<name> = <module>.<name>

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100617/fa34b2d7/attachment-0001.sig>


More information about the Python-list mailing list