python - Can from <module> import * not work sometimes? -


if have python module has bunch of functions, this:

#funcs.py def foo() :     print "foo!"  def bar() :     print "bar!" 

and have module designed parse list of functions string , run functions:

#parser.py funcs import *  def execute(command):     command = command.split()     c in command:         function = globals()[c]         function() 

then can open python , following:

>>> import parser >>> parser.execute("foo bar bar foo") foo! bar! bar! foo! 

i want add convenience function funcs.py allows list of functions called function itself:

#funcs.py (new version) import parser  def foo() :     print "foo!"  def bar() :     print "bar!"  def parse(commands="foo foo") :     parser.execute(commands) 

now can recursively parse parser itself:

>>> import parser >>> parser.execute("parse") foo! foo! >>> parser.execute("parse bar parse") foo! foo! bar! foo! foo! 

but reason can't run parse funcs, key error:

>>> import funcs >>> funcs.parse("foo bar") traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "funcs.py", line 11, in parse     parser.execute(commands)   file "parser.py", line 6, in execute     function = globals()[c] keyerror: 'foo' 

so though foo should imported parser.py through from funcs import * line, i'm not finding foo in globals() of parser.py when used through funcs.py. how happen?

i should point out importing parser , funcs (but in order) allows work expected:

>>> import parser >>> import funcs >>> funcs.parse("foo bar") foo! bar! 

import module_name fundamentally different from module_name import * does.

the former creates global named module_name, of type module , contains module's names, accessed attributes. latter creates global each of names within module_name, not module_name itself.

thus, when import funcs, foo , bar not put globals(), , therefore not found when execute looks them.

cyclic dependencies (trying have parser import names funcs while funcs imports parser) bad. explicit better implicit. don't try create magic. tell parse() functions available.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -