简体   繁体   中英

Python/django import error

I have problems with importing function from other file.

I have files forms.py and helpers.py

My helpers.py:

from .forms import *

def check_pesel(pesel):
    sum, ct = 0, [1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1]
    for i in range(11):
        sum += (int(pesel[i]) * ct[i])
    return (str(sum)[-1] == '0')

def check_nip(nip_str):
    nip_str = nip_str.replace('-', '')
    if len(nip_str) != 10 or not nip_str.isdigit():
        return False
    digits = map(int, nip_str)
    weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
    check_sum = sum(map(mul, digits[0:9], weights)) % 11
    return check_sum == digits[9]

and forms.py:

from .helpers import *

#(...) rest of code

When I try to use check_pesel() in forms.py I get:

global name 'check_pesel' is not defined

when I change from .helpers import check_pesel, check_nip I get:

cannot import name check_nip

How can I fix this?

When you attempt a circular import ( .forms imports .helpers and .helpers imports .forms ) Python cannot import the first module again (since it's already importing it) and that's why you get the error you describe. You must rearrange your code unfortunately (it has nothing to do with Django in this case)

As other people have pointed out, this is a problem with you using circular imports. Circular imports/dependencies are not explicitly disallowed in python, but you have to know how to do them correctly.

If you were to have a third file which imported * from both forms and helpers, you would find that the behavior changed depending on which order you imported them in. If you imported forms first then helpers would not have access to anything from forms and if you imported helpers first then forms would not have access to anything from helpers.

The easy solution to you problem, in this case, is to use this approach:

# file y.py
import x
def foo():
    x.bar()

# file x.py
import y
def bar():
    y.foo()

Because it is not using "from x import *" this will work with circular dependencies when the dependencies are not accessed during import. (In my example I only use the dependencies inside the body of functions which are not called during import so it is OK)

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