簡體   English   中英

Python / Django導入錯誤

[英]Python/django import error

我從其他文件導入功能時遇到問題。

我有forms.py和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]

和forms.py:

from .helpers import *

#(...) rest of code

當我嘗試在forms.py中使用check_pesel()時,我得到:

global name 'check_pesel' is not defined

當我從.helpers import check_pesel更改時,check_nip得到:

無法導入名稱check_nip

我怎樣才能解決這個問題?

當您嘗試進行循環導入( .forms導入.helpers.helpers導入.forms )時,Python無法再次導入第一個模塊(因為它已經導入了),所以這就是您所描述的錯誤的原因。 不幸的是,您必須重新排列代碼(在這種情況下,它與Django無關)

正如其他人指出的那樣,這是使用循環導入的問題。 在python中沒有明確禁止循環導入/依賴關系,但是您必須知道如何正確執行它們。

如果要從第三個文件中同時從表單和助手中導入*,您會發現行為隨導入順序而改變。如果先導入表單,則助手將無法訪問表單中的任何內容,並且您首先導入了助手,然后表單將無法訪問助手的任何內容。

在這種情況下,針對您的問題的簡單解決方案是使用以下方法:

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

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

因為它不使用“ from x import *”,所以在導入期間未訪問依賴項時,它將與循環依賴項一起使用。 (在我的示例中,我僅使用導入期間未調用的函數體內的依賴項,因此可以)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM