Skip to main content
 首页 » 编程设计

python之如何限制可以传递给方法参数的允许值(使用类型提示允许静态代码分析)

2025年05月04日16三少

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

my_request(protocol_type, url) 

使用类型提示我可以写:

my_request(protocol_type: str, url: str) 

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

请您参考如下方法:

一种方法是在方法中编写代码来验证传入的值是“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