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):
...
你可以修改我的装饰器来实现你想要的。
添加回答
举报