Reputation: 313
I am new to python, and I have a question.
I want to keep all variables in one file, and the methods in another.
This is what I am thinking:
file1.py
:
import calculations
a = 3
b = 2
c = subtraction()
print c
calculations.py
:
def subtraction():
answer = a-b
return answer
The methods in calculations.py
have to be utilized in file1.py
, and they need to use the "global" variables stated in file1.py
.
Where does my logic fail?
Upvotes: 0
Views: 56
Reputation: 1122152
This is not how globals in Python work. Globals are limited to the module they are defined in.
You'll have to pass in your variables as arguments to subtraction()
instead:
def subtraction(a, b):
return a - b
and
c = subtraction(a, b)
Note that you imported the module, so you need to refer to the function as an attribute of that module:
c = calculations.subtraction(a, b)
Alternatively, import just the function into your module namespace:
from calculations import subtraction
Upvotes: 3
Reputation: 798686
When the function is defined, the compiler assigns its "global" scope to be that of the module it was defined in. This scope does not change even though a reference to the function exists within another module, since the function itself is unchanged.
Upvotes: 3