[英]Pythonic Way To Check for A Parameter Type
我正在研究一個小方面的工作,並制作了一些課程和方法。 其中一個類代表我們庫存中的貨架,另一個代表貨架上的每個貨架。 我有一個方法來添加一個新的bin到架子,我添加了一些邏輯,以確保它被添加到架子之前傳遞一個Location對象(現在我在開發之前使用列表,然后將所有內容移動到數據庫)。
但是我剛讀了一本Python書,我認為處理異常通常會更好,而不是添加額外的代碼。 我刪除了邏輯,看看我會得到什么錯誤,但我沒有得到任何東西,它允許一個字符串代替Location對象。
是否有更多的Pythonic方法來強制執行參數的類型?
我有什么貨架:
class CrossDock:
locations = []
def add_location(self, location):
if isinstance(location, Location): #if this is commented out it will take what ever is passed to it
self.locations.append(location)
else:
print("location parameter must be of type: Location. Parameter is of type" + str(type(location)))
有沒有辦法用try / except塊做到這一點?
向調用者傳播異常。 這迫使類的用戶,當他們濫用類來解決無效的類型。 打印無用,因為它不強制執行接口合同。
class CrossDock(object):
def __init__(self):
self.locations = []
def add_location(self, location):
if isinstance(location, Location):
self.locations.append(location)
else:
raise TypeError("location must be Location, got: " +
repr(type(location)))
您最終可能遇到的異常會發生在您的代碼中的其他位置,當您嘗試使用Location實例但在其中找到其他內容時。 當參數來自不可靠的源時,檢查參數沒有任何問題。 這會將異常置於問題的根源,而不是代碼中可能更難診斷的輔助位置。
您可能會做很多事情,只提出異常而不是打印錯誤。
def add_location(self, location):
if not isinstance(location, Location):
tmpl = "location parameter must be of type: Location, got %s"
raise TypeError(tmpl % str(type(location)))
... do other processing here after guarding check ...
如果您無法控制調用代碼,則此類檢查最合適。 如果您只想捕獲自己編寫的編程錯誤,可以使用斷言:
def add_location(self, location):
assert isinstance(location, Location), "location must be of type: Location"
... do other processing here
反對進行參數類型檢查的建議旨在允許代碼中的最大靈活性,例如,如果有人想要傳入與位置具有相同方法的對象。 檢查硬編碼類型會引發異常,即使代碼可以正常工作。
最pythonic的方式是不打字檢查......一切都是鴨子打字。
在try / except塊中使用assert
class Location():
pass
class CrossDock:
locations = []
def add_location(self, location):
try:
assert(isinstance(location, Location))
self.locations.append(location)
print("added")
except AssertionError:
print("error: Parameter is of type" + str(type(location)))
c = CrossDock()
loc = Location()
c.add_location("2")
c.add_location(loc)
在第一次add_location
調用時將失敗
location parameter must be of type: Location. Parameter is of type<type 'str'>
added
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.