Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inject a module into an imported module's globals?

Tags:

python

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:

  • Is it possible to inject 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.

like image 682
Steve Lorimer Avatar asked Dec 06 '16 21:12

Steve Lorimer


1 Answers

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.

like image 162
kindall Avatar answered Oct 04 '22 20:10

kindall