Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in Python's documentation?

I am reading http://docs.python.org/2/tutorial/modules.html#more-on-modules and wonder if the following is correct:

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.

Apparently not:

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

See http://ideone.com/cLK09v for an online demo.

So, is it a bug in the Python's documentation or I don't understand something?

like image 448
piokuc Avatar asked Mar 07 '13 23:03

piokuc


People also ask

How stable is Python in fixing bugs?

Python is a mature programming language which has established a reputation for stability.


1 Answers

Yes, this is a documentation error. The import statement imports the names to the current namespace. Usually import is used outside of functions and classes, but as you've discovered, it does work within them. In your example function, the module is imported into the function's local namespace when the function is called. (Which you didn't do, but that wouldn't make it available outside the function anyway.)

The global keyword does work here, however:

def foo():
    global sys
    import sys

foo()
sys.path
like image 144
kindall Avatar answered Sep 27 '22 18:09

kindall