问答 Python 方法能在参数位置就设定传入参数的可选择范围吗?

lscrr · 2023年06月20日 · 最后由 lscrr 回复于 2023年06月29日 · 6918 次阅读

共收到 7 条回复 时间 点赞

我理解一种是你在函数内进行判断来过滤这个参数的范围。另一种方法就是使用装饰器来限制这个参数的范围,不过会稍微麻烦一点点

如果你的需求是让它无法传入的话,装饰器应该可以实现

4楼 已删除

1、使用类型注解,把参数限定的内容换成枚举类型,在 ide 中传参如果不是指定的枚举类型,会给出提示

from enum import Enum

class StrEnum(Enum):
    one = '1'
    two = '2'
    three = '3'
    four = '4'
    five = '5'

def func(string: StrEnum) -> None:
    ...

2、方法添加注释,对参数范围进行说明,方法里面对参数做判断,不符合范围的抛出异常

安装 pydantic

pip install 'pydantic[dotenv]'

执行以下代码

from pydantic import Field, validate_arguments, ValidationError
@validate_arguments
def my_func(i: int = Field(..., ge=1, le=100)):
    # 你的函数逻辑在这里
    print(f"Input {i} is within the valid range.")

try:
    my_func(50)  # 正确的输入,应该打印"Input 50 is within the valid range."
    my_func(150)  # 错误的输入,会引发ValidationError异常
except ValidationError as e:
    print(f"Invalid input: {e}")

输出

Input 50 is within the valid range.
Invalid input: 1 validation error for MyFunc
i
  ensure this value is less than or equal to 100 (type=value_error.number.not_le; limit_value=100)

感谢各位!

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册