简体   繁体   中英

How do I bypass a circular import?

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.

The best way to do this is to just pass the variable as an argument to your function. Eg:

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 . Eg:

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM