I have a file hello.py
which has a function hello()
hello.py
:
def hello():
print "hello world"
I have another file test.py
which imports hello
, and calls the function.
test.py
:
from hello import *
def run():
hello()
if __name__ == '__main__':
run()
If I run test.py
through python, it works as expected:
$ python test.py
hello world
Now, however, I edit test.py
, and remove the import statement:
test.py
:
def run():
hello() # hello is obviously not in scope here
if __name__ == '__main__':
run()
I introduce a 3rd file, run.py
, which imports both hello.py
and test.py
run.py
:
from hello import *
from test import *
if __name__ == '__main__':
run()
Naturally this does not work, as hello()
is not in test.py's
scope.
$ python run.py
Traceback (most recent call last):
File "run.py", line 5, in <module>
run()
File "test.py", line 4, in run
hello()
NameError: global name 'hello' is not defined
Question:
hello()
into test.py's
scope from run.py
, without having run.py
import hello.py
?I'm happy using lower level functionality, such as the imp
module, if that is what is required.
Yes. A module's attributes are its globals, so you can just poke it in there.
import test
import hello
test.hello = hello.hello
I'll reiterate wim's comment that this is generally not a great idea.
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