xenocyon
xenocyon

Reputation: 2498

Python: how to enable a called file to access functions defined in the calling file?

I have two program files: a.py and b.py. The former calls the latter, but the latter expects to have access to some functions defined in the former. I can't seem to get this to work properly.

To give a concrete, simple example:

a.py

def onemore(x):
    return x+1

import b
print "result is:", b.twomore(5)

b.py:

def twomore(x):
    import a
    return a.onemore(x)+1

Desired behavior from running a.py:

result is: 7

Actual behavior from running a.py:

result is: result is: 7

7

I have tried a bunch of different import structures, checked other answers posted here, but without any luck. The above is actually the best result I've been able to achieve, but it seems to run things twice, which is not permissible for my actual use case.

I recognize the circular nature of the imports here, but surely this is a solvable problem?

The practical motivation for this is: I'm trying to call an auxiliary routine from within a program, that needs access to basic functions defined in the program.

Upvotes: 0

Views: 33

Answers (2)

Ownaginatious
Ownaginatious

Reputation: 797

Your code

print "result is:", b.twomore(5)

gets run when import a is executed. Try putting it inside a block that only runs it if the file is being run directly from your console.

if __name__ == "__main__":
    print "result is:", b.twomore(5)

That should fix it, but you should generally try to avoid circular dependencies if you can.

Upvotes: 3

lint
lint

Reputation: 98

you should only import onemore from a (from a import onemore), otherwise import a also runs the print expression

Upvotes: 0

Related Questions