Why import only at module level?

Steve dippyd at yahoo.com.au
Tue Feb 24 23:07:26 EST 2004


Michael Hudson wrote:

>>   def frob(x):
>>      import re
>>      if re.search('sdf[234]xyz', x): ...
>>
>>instead preferring that you pollute your module's global namespace
>>with the names of all your imports.  What's the point of that?
> 
> What's the problem with that?

(1) It breaks code encapsulation. Well, perhaps 
"breaks" is too strong a word, but it makes data hiding 
more difficult. Unless you jump through hoops to remove 
all traces of the objects you import, modules that you 
import will be visible to those that import you.

(2) It is messy. The whole point of nested scopes is to 
make objects visible only to the objects that need 
them. If only one function needs the import, why force 
it to be visible to all the others?

(3) There was clearly a need (or at least a wish) to be 
able to hide imported objects from importing modules. 
The usual way of doing this is:

from spam import public as _notpublic

Making the import local to the calling function works 
well too.

I sometimes delete the binding when I'm done:

from spam import public
# use public in here
del public

although there are disadvantages to this method.



[snip]
 > The problem HERE is for nested scopes; it's
 > impossible to know in
 >
 > def f():
 >     from baz import *
 >     def g():
 >         return y
 >
 > where y is coming from (i.e. is it a captured 
binding > or a global).

Why is this any different from the following top-level 
code:

# module baz:
y = "spam spam spam"

 >>> y= "I don't like spam"
 >>> from baz import *

Where is the binding y coming from? The question of 
whether this code is at the top-level or in a function 
definition is a red herring.


It seems to me that forbidding imports except at the 
top level is an arbitrary restriction. Using import 
insided function definitions might not work for some 
people, but it works for others.



-- 
Steven D'Aprano





More information about the Python-list mailing list