Python: Namespaces with Module Imports -


i learning python , still beginner, although have been studying year now. trying write module of functions called within main module. each of functions in called module needs math module run. wondering if there way without importing math module inside called module. here have:

main.py:

from math import * import module1  def wow():      print pi   wow() module1.cool() 

module1.py:

def cool():      print pi 

when running main.py get:

3.14159265359  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' not defined 

what i'm having hard time understanding why name error when running main.py. know variable pi becomes global main module upon import because wow can access it. know cool becomes global main module upon import because can print module1.cool , <function cool @ 0x02b11af0>. since cool inside global namespace of main module, shouldn't program first inside function cool variable pi, , when doesn't find there, inside main module variable pi , find it there?

the way around know of import math module inside module1.py. don't idea of that, though because makes things more complicated , fan of nice, simple code. feel close grasping namespaces, need on one. thanks.

as traceback shows, problem isn't in main.py, 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' not defined 

in other words, in module1, there no global name pi, because haven't imported there. when from math import * in main.py, imports math module's namespace main module's namespace, not every module's namespace.

i think key thing you're missing here each module has own "global" namespace. can bit confusing @ first, because in languages c, there's single global namespace shared extern variables , functions. once past assumption, python way makes perfect sense.

so, if want use pi module1, have from math import * in module1.py. (or find other way inject it—for example, module1.py from main import *, or main.py module1.pi = pi, etc. or cram pi magic builtins/__builtin__ module, or use various other tricks. obvious solution import want imported.)


as side note, don't want from foo import * anywhere except interactive interpreter or, occasionally, top-level script. there exceptions (e.g., few modules explicitly designed used way), rule of thumb either import foo or use limited from foo import bar, baz.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -