I am dealing with some python code automatically generated for me. I want to avoid manually editing these python files & hence this question/issue:
foo.py:
def foo():
print "foo"
boo.py:
def boo():
foo.foo() # <-- global name 'foo' not defined
print "boo"
bar.py:
import foo
import boo
def bar():
boo.boo()
print "bar"
Execution of:
python.exe bar.py
gives an error that boo
did not find foo
. But bar is importing both foo
& boo
. Shouldn't foo
be automatically available to boo
?
Is there a way to do so? As said boo.py is automatically generated for me & I want to avoid adding import foo to boo.py.
Thanks.
The scope of an imported variable (or function/module/class) is the same scope of where the import is started (imports don't need to be at the top of the file), but this is unrelated to your error.
Python is a regular language, which means that function definitions, class definitions, import statements etc. mostly work at any scope.
append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
But bar is importing both foo & boo. Shouldn't foo be automatically available to boo?
No it shouldn't: import
, like any other way to bind a name, binds that name in a single, specific scope, not "in all scopes you could ever possibly want it in".
Is there a way to do so? As said boo.py is automatically generated for me & I want to avoid adding import foo to boo.py
There's one very bad hack -- I wouldn't want to live with it (I'd much rather pour my energy into getting that totally broken code generator that makes boo.py
fixed -- if it has such a huge bug as missing a crucial needed import, what other horrors can it have in store?!), but, hey, it ain't my funeral...;-)
Have bar.py
start...:
import foo
import boo
import __builtin__
__builtin__.foo = foo
This way you've made identifier foo
a "fake, artificial built-in name" (the only kind of name that is available from every scope, unless shadowed by other intervening bindings of the name
in closer scopes) referring to the module foo
.
NOT recommended procedure, just a temporary workaround for the horrible, glaring bug in the code generator that builds boo.py
. Get that bug fixed so you can retire this hack ASAP!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With