Raa*_*mEE 2 python enums enumeration type-hinting
在 Python 3 中,我想限制传递给此方法的允许值:
my_request(protocol_type, url)
Run Code Online (Sandbox Code Playgroud)
使用类型提示我可以写:
my_request(protocol_type: str, url: str)
Run Code Online (Sandbox Code Playgroud)
所以协议和 url 仅限于字符串,但我如何验证protocol_type只接受有限的一组值,例如'http'和'https'?
一种方法是在方法中编写代码来验证传入的值是“http”还是“https”,内容如下:
if (protocol_type == 'http') or (protocol_type == 'https'):
Do Something
else:
Throw an exception
Run Code Online (Sandbox Code Playgroud)
这将在运行时正常工作,但不会在编写代码时提供问题的指示。
这就是为什么我更喜欢使用 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')
Run Code Online (Sandbox Code Playgroud)
输出:
<enum 'ProtocolEnum'>
http
HTTP
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |