如何限制可以传递给方法参数的允许值

在 Python 3 中,我想限制传递给此方法的允许值:

my_request(protocol_type, url)

使用类型提示我可以写:

my_request(protocol_type: str, url: str)

所以协议和 url 仅限于字符串,但我如何验证protocol_type它只接受有限的一组值,例如'http''https'


肥皂起泡泡
浏览 216回答 3
3回答

LEATH

一种方法是在方法中编写代码来验证传入的值是“http”还是“https”,如下所示:if (protocol_type == 'http') or (protocol_type == 'https'):&nbsp; Do Somethingelse:&nbsp; Throw an exception这将在运行时正常工作,但在编写代码时不会提供问题指示。这就是为什么我更喜欢使用 Enum 以及 Pycharm 和 mypy 实现的类型提示机制的原因。对于下面的代码示例,您将在 Pycharm 的代码检查中收到警告,请参阅随附的屏幕截图。屏幕截图显示,如果您输入的值不是枚举,您将收到“预期类型:...”警告。代码:"""Test of ENUM"""from enum import Enumclass ProtocolEnum(Enum):&nbsp; &nbsp; """&nbsp; &nbsp; ENUM to hold the allowed values for protocol&nbsp; &nbsp; """&nbsp; &nbsp; HTTP: str = 'http'&nbsp; &nbsp; HTTPS: str = 'https'def try_protocol_enum(protocol: ProtocolEnum) -> None:&nbsp; &nbsp; """&nbsp; &nbsp; Test of ProtocolEnum&nbsp; &nbsp; :rtype: None&nbsp; &nbsp; :param protocol: a ProtocolEnum value allows for HTTP or HTTPS only&nbsp; &nbsp; :return:&nbsp; &nbsp; """&nbsp; &nbsp; print(type(protocol))&nbsp; &nbsp; print(protocol.value)&nbsp; &nbsp; print(protocol.name)try_protocol_enum(ProtocolEnum.HTTP)try_protocol_enum('https')输出:<enum 'ProtocolEnum'>httpHTTP

Cats萌萌

您可以检查函数中的输入是否正确:def my_request(protocol_type: str, url: str):&nbsp; &nbsp; if protocol_type in ('http', 'https'):&nbsp; &nbsp; &nbsp; &nbsp; # Do x&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return 'Invalid Input'&nbsp; # or raise an error

喵喵时光机

我想你可以使用装饰器,我有类似的情况,但我想验证参数类型:def accepts(*types):&nbsp; &nbsp; """&nbsp; &nbsp; Enforce parameter types for function&nbsp; &nbsp; Modified from https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments&nbsp; &nbsp; :param types: int, (int,float), if False, None or [] will be skipped&nbsp; &nbsp; """&nbsp; &nbsp; def check_accepts(f):&nbsp; &nbsp; &nbsp; &nbsp; def new_f(*args, **kwds):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (a, t) in zip(args, types):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if t:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; assert isinstance(a, t), \&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"arg %r does not match %s" % (a, t)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f(*args, **kwds)&nbsp; &nbsp; &nbsp; &nbsp; new_f.func_name = f.__name__&nbsp; &nbsp; &nbsp; &nbsp; return new_f&nbsp; &nbsp; return check_accepts然后用作:@accepts(Decimal)def calculate_price(monthly_item_price):&nbsp; &nbsp; ...你可以修改我的装饰器来实现你想要的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python