[Tutor] how import a module upon instantiation of a class?

Steven D'Aprano steve at pearwood.info
Mon Sep 1 16:13:35 CEST 2014


On Mon, Sep 01, 2014 at 06:46:41AM -0700, Albert-Jan Roskam wrote:

> >>      def __init__(self):
> >           global some_nonbuiltin
> >           import some_nonbuiltin
> 
> Ahh with 'global', thank you! It never crossed my mind that this 
> should be used in this case. Within functions, 'global' is only 
> required when the global variable is going to be modified. 

No! Absolutely not! 

The "global" keyword is needed when the global *name* is going to be 
re-bound to a different object, it has nothing to do with modifying 
objects. Let's see how we might "modify a variable":

py> mylist = []
py> def spam():
...     mylist.append(42)  # modifies the mylist object
...
py> spam()
py> spam()
py> print mylist
[42, 42]

Calling spam() doesn't change what the name "mylist" refers to, it's 
still the same list, but the list does get changed. If you re-bind the 
name, by default Python treats it as a local variable:

py> def eggs():
...     mylist = ["something", "else"]
...
py> eggs()
py> print mylist
[42, 42]


You need the global keyword to make eggs() consider "mylist" to be 
global rather than local:

py> def eggs():  # take two
...     global mylist
...     mylist = ["something", "else"]
...
py> eggs()
py> print mylist
['something', 'else']


The import statement performs a name binding: it creates a variable with 
the same name as the module (or the name given by "as").

py> math  # name doesn't exist yet
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
py> import math
py> math  # now the name exists, same as if we said "math = ..."
<module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'>


So what happens if you put an import inside a function? It creates a 
variable with the name of the module. Since it is inside a function, it 
is a *local* variable, which makes it invisible to anything outside of 
that module:

py> def cheese():
...     import string
...
py> cheese()
py> string
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined

To make it a global name, you need the global keyword:

py> def cheese():  # take two
...     global string
...     import string
...
py> cheese()
py> string
<module 'string' from '/usr/local/lib/python2.7/string.pyc'>



-- 
Steven


More information about the Tutor mailing list