d1337
d1337

Reputation: 2753

how to define a global variable to be used in a function of an imported file?

Given two files A.py and B.py, A imports B.py and calls a function 'foo' defined in it. If 'foo' requires a global variable to keep track of itself, how and where should it be defined? Thanks

Upvotes: 0

Views: 56

Answers (1)

Elazar
Elazar

Reputation: 21645

In B.py, since this is the global scope for foo():

var = 0

def foo():
    global var
    #use var here

But if foo() needs a variable to keep track of something, it should probably be a method in a class (a function with a state is not really a function).

Another solution is to add a foo.var variable:

def foo():
    'use foo.var here'
    # things

foo.var = 0

Depending on your intentions, it may be the case that what you are looking for is not a function but a generator function.

Upvotes: 1

Related Questions