首页 > 解决方案 > How to get object from file that imported another file?

问题描述

Say I have a python file called fileOne.py that imports fileTwo.py. Is there a way for fileTwo.py to access the objects from fileOne.py dynamically? So fileTwo.py doesn't need to know the name of the file that will import it, and instead can do something like this: FILE_THAT_IMPORTED_ME.myFunction().

Basically I want to know if there is a way to access objects from the 'parent' file that is importing a script, from said script.

标签: pythonpython-3.ximportpython-import

解决方案


You can access the file which imported you by doing import __main__ and __main__ will contain the parent module.

a.py#

import b
print(b)

b.py#

import __main__
print(__main__)

Executing a.py will result in

<module '__main__' from '/home/jonatan/PycharmProjects/tests/test/a.py'>
<module 'b' from '/home/jonatan/PycharmProjects/tests/test/b.py'>

Note that __main__ is being printed before b since the module b has to complete its loading before continue the file a.


推荐阅读