Reputation: 182
I have a python file with all the functions I want to use, while I have another one for my main code. We'll call the function one "functions.py" and the main one "main.py".
The functions in my functions.py file require variables from the main.py file. When I try to import one to another I get a circular import error.
Example:
main.py:
from functions import func
variable = 10
func()
functions.py:
from main import variable
def func():
variable += 1
Now I want variable to be 11.
I understand why this happens but is there any way to make this work?
Sorry for my rookie questions, and thank you in advance.
Upvotes: 0
Views: 233
Reputation: 125
The best way to do this is to just pass the variable as an argument to your function. E.g.:
main.py:
from functions import func
variable = 10
variable = func(variable)
functions.py:
def func(variable):
variable += 1
return variable
Even if you could import it, or if you just moved func
into the main.py
file, Python would throw an UnboundLocalError
complaining that variable
is used before it's assigned since the variable
in func
is not the same as the variable
outside of func
. E.g.:
>>> v = 10 # outer v
>>> def func():
v += 1 # inner v
>>> func()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
func()
File "<pyshell#3>", line 2, in func
v += 1
UnboundLocalError: local variable 'v' referenced before assignment
>>>
Here, "outer v" is in the global scope, while "inner v" is in func
's scope, so they do not reference the same variable. For further reading, I'd encourage you to look up how scopes work in Python.
Upvotes: 2