multiple import of a load of variables

Jeff Shannon jeffshannon at gmail.com
Wed Mar 16 16:27:18 EST 2005


Torsten Bronger wrote:

> Hallöchen!
> 
> "Fuzzyman" <fuzzyman at gmail.com> writes:
> 
> 
>>[...]
>>
>>I'm not entirely clear what you are trying to do
> 
> 
> The following: "variables.py" looks like this
> 
> a = 1
> b = 2
> 
> Then I have helper_a.py, helper_b.py, and helper_c.py which begin
> with
> 
> from variables import *
> 
> And finally, my_module.py starts with
> 
> from variables import *
> from helper_a.py import *
> from helper_c.py import *
> from helper_c.py import *
> 
> Now imagine that variables.py contained not only two but hundreds of
> variables.  Is this then still the most effective approach?

Ugh.  I really don't like the 'from module import *' approach in any 
case, but here, you're binding each name from variables.py at least 
seven times.  Now, it's not like binding names is all *that* 
expensive, but still... I'd call this a code smell.

You say that users of my_module.py may need direct access to these 
variables; to do that well, it does make some sense that my_module 
should import * from variables.  However, I doubt there's any good 
justification for importing the helper modules that way, nor for 
importing * from variables in each of the helper modules.

If you use normal imports in those cases, then once variables.py has 
been loaded into sys.modules (i.e. imported for the first time), you 
create n+3 name bindings as opposed to the 7*n bindings your method is 
creating, where n is the number of names in variables.py.  (The '+6' 
is the 'variables' name in each of the helper modules.)

More importantly, you get clearer code that's easier to maintain and 
troubleshoot.  This fact is far more important than the cost of 
creating name bindings, or any other form of 'efficiency' that is 
likely to apply.  As far as I'm concerned, if you're just going to 
'import *' your helper modules, you might as well leave the whole mess 
as one big file, because you're throwing away almost all of the 
benefits of dividing it into modules.

Jeff Shannon




More information about the Python-list mailing list