Advice on the style to use in imports
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Sat Aug 30 10:04:58 EDT 2008
Marco Bizzarri:
> I'm just confused because PEP8 seems to suggest that the from module
> import Class style is acceptable; is there a big "if you know what are
> doing" before, which I'm unable to see?
from somemodule import somename
is often acceptable IHMO, but there are some things to consider:
- you and the person that reads your code have to remember where
somename comes from. So you can do it for well known names like izip
or imap, but if you import lots of names from lots of modules, things
may become too much complex. So often it can be better to import just
the modules, and use somemodule.somename.
- somemodule.somename is longer to write and to read, and if it's
repeated many times it may worsen the program readability, making
lines of code and expressions too much long and heavy. So you have to
use your brain (this means that you may have to avoid standard
solutions). Note that you can use a compromise, shortening the module
name like this:
import somemodule as sm
Then you can use:
sm.somename
- somemodule.somename requires an extra lookup, so in long tight loops
(if you don't use Psyco) it slows down the code. This can be solved
locally, assigning a local name into a function/method (or even in
their argument list, but that's a hack to be used only once in a
while):
localname = somemodule.somename
Bye,
bearophile
More information about the Python-list
mailing list