簡體   English   中英

調用函數時出現 NameError(尋找一種更簡潔的方式來編寫代碼)

[英]NameError while calling a function (looking for a cleaner way to write the code)

我有一個文件,其中包含 python 變量形式的提取數據。 我希望這些數據總是以 2 個變量的形式出現(檢查、輸出檢查)。 問題是在某些情況下,數據要么不完整(只是檢查變量),要么無法提取數據(意味着根本沒有變量)。根據提取的數據,文件的內容總是不同的。 下面是一個文件示例:

check_1 = "Warning, the check has failed"
output_check_1 = "Here is a more detailed result."
check_2 = "Warning, the check has failed"
#There is no output_check_2 variable
#There is no check_3 at all

接下來,函數將根據文件中的數據生成報告:

def create_report(check, output_check):
 if check.startswith("Warning"):
   print(check)
   if output_check:
    print(output_check)
   else:
    print("Sorry, couldn't get a more detailed result")
 else:
   print("Check was successful.")

#Let's call the function
create_report(check_1, output_check_1) #Works
create_report(check_2, output_check_2) #-> NameError because in this case output_check_2 does not exist 
create_report(check_3, output_check_3) #-> NameError because none of the arguments exist

作為修復,我想出了以下內容:

try:
 create_report(check_2, output_check_2)
except NameError:
 output_check_2 = ""
 try:
  create_report(check_2, output_check_2)
 except NameError:
  print("Error - data could not be extracted from the server!")

這樣,如果參數 2 (output_check_2) 丟失,我將只收到沒有詳細數據的檢查結果,如果兩個參數都丟失 (check_3, output_check_3) 我將收到一個錯誤,指出數據無法在全部。

問題是我發現我的“修復”相當野蠻,我正在尋找一種更簡潔的方式來獲得相同的結果,因為該函數將在執行過程中被多次調用。

編輯:變量來自我在腳本開始時導入的 extraced_data.py 文件。 不幸的是,我無法訪問在第一個位置生成變量的腳本,因此遇到了這個問題。

您也可以通過 (*argv) 而不是 (check, output_check)。 這允許您將任意數量的參數傳遞到您的函數中。

def create_report(*argv):
    if argv[0].startswith("Warning"):   # argv[0] is your 'check' variable
        print(argv[0])
        if len(argv) > 1:    
            print(argv[1])   # argv[1] is your output_check variable
        else:
            print("No more info.")
    else:
            print("Check successful")

假設無法修復數據的存儲方式* ,您可以使用getattr來處理丟失的數據。 我假設你正在做這樣的事情來導入:

from dataScript import *

把它改成這樣:

import dataScript

然后你可以這樣做:

check1 = getattr(dataScript, "check1", None)  # Will default to None if it doesn't exist
if check1 is not None:
    create_report(check_1, getattr(dataScript, "output_check1", None))

或者,如果您使用的是 Python 3.8+ 並且check變量永遠不會是空字符串:

if check1 := getattr(dataScript, "check1", None):
    create_report(check_1, getattr(dataScript, "output_check1", None))

如果您有任意數量的這些變量,則可能需要使用循環。 就像是:

for i in range(MAX_VARS):
    n = i + 1
    if check := getattr(dataScript, f"check{n}", None):
        create_report(check_, getattr(dataScript, f"output_check{n}", None))

其中MAX_VARS是您期望的最高變量。


*這里的輸入格式確實是問題所在。 使用 Python 腳本作為有時只有正確數據的數據庫似乎是真正的問題。 我上面的解決方案只是一種解決方法。

您所要做的就是更改create_report函數。

def create_report(check, output_check):
 if not check:
   print("Error - data could not be extracted from the server!")
   return
 if not output_check:
    output_check = ""

 if check.startswith("Warning"):
   print(check)
   if output_check:
    print(output_check)
   else:
    print("Sorry, couldn't get a more detailed result")
 else:
   print("Check was successful.")

現在您可以在沒有try-except塊的情況下調用該函數。

暫無
暫無

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

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