Advice on the style to use in imports

Marco Bizzarri marco.bizzarri at gmail.com
Sat Aug 30 13:28:53 EDT 2008


Hi bearophile

On Sat, Aug 30, 2008 at 4:04 PM,  <bearophileHUGS at lycos.com> wrote:


>
> 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.

Yes, that's true; but when I see that I need so many symbols from
another module, I take that as an hint that either my module is doing
too many things, and it should be splitted, or it is tightly coupled
to that module... actually, being forced to write all the imports in
that way was a tool into inspecting the dependencies in our project.

> - 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

it is not a problem to have special cases, as long as they are
"special"; I'm looking for more or less accepted solutions; of course
any project has some area where it is better to follow readability
over standards; I'm just trying to understand the standards, then I
will deviate from them.

I feel like I'm learning to drive: first I learn the rules, then I
learn the exceptions ;)

> - somemodule.somename requires an extra lookup, so in long tight loops

The slowdown was what in the first place made me import all the names
directly; but I'm not afraid too much from that, right now.


> (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
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks again for sharing your thoughts with me, bearophile.


-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
http://notenotturne.blogspot.com/



More information about the Python-list mailing list