Search code examples
pythonpython-3.ximportpackagepython-import

Package calling functions from importing program


Can a package call a function inside of the file that is importing it?

For example:

Code of file1.py

import file2

def onstart():
    print('Hello World!')

Code of file2.py

# ... something
onstart()

Then if I run file1, I want the output to be

Hello World!

I tried just calling it in file2.py, but that gave an error

NameError: name 'onstart' is not defined


Solution

  • I found a way. If I import __main__ in file2 and make a class in file2, if I call that class in file1, I can run functions from file1.

    In file1

    import file2
    
    test = file2.Test()
    
    def onstart():
        print('Hello World!')
    
    test.run()
    

    In file2

    import __main__
    
    class Test:
        def run(self):
            if hasattr(__main__,'onstart') and __main__.onstart:
                __main__.onstart()
    

    Output

    Hello World!

    I found this answer by searching in Ursina's source code.