As the trace shows, the problem is not in main.py , but in module1.py :
Traceback (most recent call last): File "Z:\Python\main.py", line 10, in <module> module1.cool() File "Z:\Python\module1.py", line 3, in cool print pi NameError: global name 'pi' is not defined
In other words, there is module1 global name pi in module1 because you did not import it there. When you do from math import * in main.py , it simply imports everything from the math module namespace into the main module namespace, and not into each module namespace.
I think the key thing that you are missing here is that each module has its own โglobalโ namespace. This can be a little confusing at first, because in languages โโlike C, there is one global namespace shared by all extern variables and functions. But once you overcome this assumption, the Python path makes sense.
So, if you want to use pi from module1 , you need to do from math import * in module1.py . (Or you could find some other way to insert it - for example, module1.py could do from main import * , or main.py could do module1.pi = pi , etc. Or you could paste pi into magic builtins / __builtin__ or use other tricks. But the obvious solution is to make import where you want to import it.)
As a side note, you usually don't want to do from foo import * anywhere except an interactive interpreter, or sometimes a top-level script. There are exceptions (for example, several modules are explicitly intended for use in this way), but the rule of thumb applies to either import foo or the restricted from foo import bar, baz .
abarnert Apr 08 '13 at 22:28 2013-04-08 22:28
source share