简体   繁体   English

Python / Django导入错误

[英]Python/django import error

I have problems with importing function from other file. 我从其他文件导入功能时遇到问题。

I have files forms.py and helpers.py 我有forms.py和helpers.py文件

My helpers.py: 我的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: 和forms.py:

from .helpers import *

#(...) rest of code

When I try to use check_pesel() in forms.py I get: 当我尝试在forms.py中使用check_pesel()时,我得到:

global name 'check_pesel' is not defined

when I change from .helpers import check_pesel, check_nip I get: 当我从.helpers import check_pesel更改时,check_nip得到:

cannot import name check_nip 无法导入名称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. 当您尝试进行循环导入( .forms导入.helpers.helpers导入.forms )时,Python无法再次导入第一个模块(因为它已经导入了),所以这就是您所描述的错误的原因。 You must rearrange your code unfortunately (it has nothing to do with Django in this case) 不幸的是,您必须重新排列代码(在这种情况下,它与Django无关)

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. 在python中没有明确禁止循环导入/依赖关系,但是您必须知道如何正确执行它们。

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. 因为它不使用“ from x import *”,所以在导入期间未访问依赖项时,它将与循环依赖项一起使用。 (In my example I only use the dependencies inside the body of functions which are not called during import so it is OK) (在我的示例中,我仅使用导入期间未调用的函数体内的依赖项,因此可以)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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