The binding operator, and what gets bound to what

Ned Batchelder ned at nedbatchelder.com
Fri Dec 5 07:06:11 EST 2014


On 12/5/14 4:53 AM, Steven D'Aprano wrote:
> Oh, I learned something new: strictly speaking, this is implementation-
> dependent and not guaranteed to work in the future!
>
> def func():
>      global math
>      import math

I don't think this is implementation-dependent.  The import statement is 
an assignment to a name (as are class, def, for, with-as and except-as). 
  Where that name is scoped is the same for all of them, and does not 
depend on the implementation.  The usual behavior of locals and globals 
happens for all of them:

 >>> import math
 >>> math
<module 'math' from '/blah/.../math.so'>
 >>> def f():
...   print math
...   import math
...
 >>> f()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in f
UnboundLocalError: local variable 'math' referenced before assignment


 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
 >>> def f():
...   global a
...   for a in range(10):
...     pass
...
 >>> f()
 >>> a
9

This also means that you can do odd things like:

    for self.foo in range(10):

or:

    for my_list[17] in range(10):

(but please don't!)


-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list