[Tutor] weird python code

D-Man dsh8290@rit.edu
Thu, 19 Apr 2001 14:01:13 -0400


On Thu, Apr 19, 2001 at 01:12:16PM -0400, Benoit Dupire wrote:
| 
| I found this on a Python website (i don' t remember where exactly)..
| but did not figure out why this does not work....
| 
| can someone explain it to me?
| thanks...
| 
| def f():
|  global path
|  from sys import *
|  print path
| 
| 
| >>> f()
| Traceback (innermost last):
|   File "<pyshell#24>", line 1, in ?
|     f()
|   File "<pyshell#23>", line 4, in f
|     print path
| NameError: path

The global statement says that 'path' should be found in the global
namespace, not the local one.  The from-import-* creates a local name
'path', I guess.  from-import-* is bad to do, except _maybe_ at module
scope (ie not inside a function).  AFAIK the Ref Man says it's
behavior is undefined (implementation specific) except at
module-level.

If you use
from sys import path
instead and leave out the 'global' statement it will work.  Or better
yet use

import sys
print sys.path

(BTW, it gives the same error in 2.0 and 2.1, but tells a little more:
    NameError: global name 'path' is not defined)

HTH,
-D