0

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.

Theo2889
  • 3
  • 3
  • `main()` is not in your first module's name-space. You could import it, but generally [you should avoid circular imports unless you are careful](http://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python). – juanpa.arrivillaga Oct 12 '16 at 17:28

1 Answers1

2

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.

Community
  • 1
  • 1
Rodolfo
  • 573
  • 2
  • 8
  • 18