Theo2889 Theo2889 - 1 month ago 9
Python Question

In python how can I call a function using an imported module

I have this module that calls main() function:

## This is mymodules ##
def restart():
r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
if r == '1':
main()
elif r == '2':
os.system('pause')


The main() is in another script that loads this module. However when it calls it says main() is not defined. essentially this is what I have in my test:

import mymodules as my
def main():
print('good')

my.restart()


When this runs I want the my.restart() to be able to call the main() defined.

Answer

For a code as simple as this one you could simply pass the main function as an argument to the restart function.

E.g.

def restart(function):
    r = input('Do you want to build another configuration file?\n1. Yes\n2. No\n')
    if r == '1':
        function()
    elif r == '2':
        os.system('pause')

And:

import mymodules as my
def main():
    print('good')

my.restart(main)

This is a popular design pattern known as a callback

However, this only works in simple examples like this. If you are writing something more complex you probably want to use objects and pass the objects instead. That way you will be able to call all multiple methods/functions from a single object.