3 回答

TA貢獻1936條經驗 獲得超7個贊
一種方法是在方法中編寫代碼來驗證傳入的值是“http”還是“https”,如下所示:
if (protocol_type == 'http') or (protocol_type == 'https'):
Do Something
else:
Throw an exception
這將在運行時正常工作,但在編寫代碼時不會提供問題指示。
這就是為什么我更喜歡使用 Enum 以及 Pycharm 和 mypy 實現的類型提示機制的原因。
對于下面的代碼示例,您將在 Pycharm 的代碼檢查中收到警告,請參閱隨附的屏幕截圖。屏幕截圖顯示,如果您輸入的值不是枚舉,您將收到“預期類型:...”警告。
代碼:
"""Test of ENUM"""
from enum import Enum
class ProtocolEnum(Enum):
"""
ENUM to hold the allowed values for protocol
"""
HTTP: str = 'http'
HTTPS: str = 'https'
def try_protocol_enum(protocol: ProtocolEnum) -> None:
"""
Test of ProtocolEnum
:rtype: None
:param protocol: a ProtocolEnum value allows for HTTP or HTTPS only
:return:
"""
print(type(protocol))
print(protocol.value)
print(protocol.name)
try_protocol_enum(ProtocolEnum.HTTP)
try_protocol_enum('https')
輸出:
<enum 'ProtocolEnum'>
http
HTTP

TA貢獻1805條經驗 獲得超9個贊
您可以檢查函數中的輸入是否正確:
def my_request(protocol_type: str, url: str):
if protocol_type in ('http', 'https'):
# Do x
else:
return 'Invalid Input' # or raise an error

TA貢獻1846條經驗 獲得超7個贊
我想你可以使用裝飾器,我有類似的情況,但我想驗證參數類型:
def accepts(*types):
"""
Enforce parameter types for function
Modified from https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments
:param types: int, (int,float), if False, None or [] will be skipped
"""
def check_accepts(f):
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
if t:
assert isinstance(a, t), \
"arg %r does not match %s" % (a, t)
return f(*args, **kwds)
new_f.func_name = f.__name__
return new_f
return check_accepts
然后用作:
@accepts(Decimal)
def calculate_price(monthly_item_price):
...
你可以修改我的裝飾器來實現你想要的。
添加回答
舉報