-1

I have a Python program A that imports another program B.

Program A has a function foo and main classes and global variables etc.

Program B has a function bar.

Program A's main function is ran user input during runtime is bar, so A calls bar: B.bar(stuff).

B.bar() tries to call A.foo(). What is the proper way of doing this?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
channon
  • 362
  • 3
  • 16
  • Why would you design it like this? It's just asking for trouble. Put `foo()` and `bar()` in the same file. – MattDMo Jun 10 '16 at 22:17
  • program b is written by the user to preprocess before calling a function. I guess B could just return the name of foo and A could call it after returning – channon Jun 11 '16 at 14:02

1 Answers1

0

The proper way is to avoid doing this as much as possible, e.g. have a third script C containing foo to avoid anything circular.

One workaround otherwise is to write B like so:

def bar():
    from A import foo
    foo()

and to not import A at the top level. This way the import only happens when bar is called so A is already fully loaded by then and you won't get an import error.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89