python 函数参数验证器 pyparamvalidate

简介: python 函数参数验证器 pyparamvalidate

pyparamvalidate 是一个简单易用的函数参数验证器。它提供了各种内置验证器,支持自定义验证规则,有助于 python

开发人员轻松进行函数参数验证,提高代码的健壮性和可维护性。

项目地址:github


安装


pip install pyparamvalidate


如果安装过程中提示 Failed to build numpy 错误:


Failed to build numpy

ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects


请先手动安装 numpy 库:

pip install numpy


使用示例


示例 1:无规则描述

from pyparamvalidate import ParameterValidator, ParameterValidationError
@ParameterValidator("name").is_string().is_not_empty()
@ParameterValidator("age").is_int().is_positive()
@ParameterValidator("gender").is_allowed_value(["male", "female"])
@ParameterValidator("description").is_string().is_not_empty()
def example_function(name, age, gender='male', **kwargs):
    description = kwargs.get("description")
    return name, age, gender, description
result = example_function(name="John", age=25, gender="male", description="A person")
print(result)  # output: ('John', 25, 'male', 'A person')
try:
    example_function(name=123, age=25, gender="male", description="A person")
except ParameterValidationError as e:
    print(e)  # output: Parameter 'name' in function 'example_function' is invalid.


示例 2:在 ParameterValidator 实例化中描述规则

from pyparamvalidate import ParameterValidator, ParameterValidationError
@ParameterValidator("name", param_rule_description="Name must be a string").is_string().is_not_empty()
@ParameterValidator("age", param_rule_description="Age must be a positive integer").is_int().is_positive()
@ParameterValidator("gender", param_rule_description="Gender must be either 'male' or 'female'").is_allowed_value(
    ["male", "female"])
@ParameterValidator("description", param_rule_description="Description must be a string").is_string().is_not_empty()
def example_function(name, age, gender='male', **kwargs):
    description = kwargs.get("description")
    return name, age, gender, description
result = example_function(name="John", age=25, gender="male", description="A person")
print(result)  # output: ('John', 25, 'male', 'A person')
try:
    example_function(name=123, age=25, gender="male", description="A person")
except ParameterValidationError as e:
    print(
        e)  # output: Parameter 'name' in function 'example_function' is invalid.     Please refer to: Name must be a string


示例 3:在 验证器 中描述规则

from pyparamvalidate import ParameterValidator, ParameterValidationError
@ParameterValidator("name").is_string("Name must be a string").is_not_empty("Name cannot be empty")
@ParameterValidator("age").is_int("Age must be an integer").is_positive("Age must be a positive number")
@ParameterValidator("gender").is_allowed_value(["male", "female"], "Gender must be either 'male' or 'female'")
@ParameterValidator("description").is_string("Description must be a string").is_not_empty(
    "Description cannot be empty")
def example_function(name, age, gender='male', **kwargs):
    description = kwargs.get("description")
    return name, age, gender, description
result = example_function(name="John", age=25, gender="male", description="A person")
print(result)  # output: ('John', 25, 'male', 'A person')
try:
    example_function(name=123, age=25, gender="male", description="A person")
except ParameterValidationError as e:
    print(e)  # Parameter 'name' in function 'example_function' is invalid.   Error: Name must be a string


可用的验证器


  • is_string:检查参数是否为字符串。
  • is_int:检查参数是否为整数。
  • is_positive:检查参数是否为正数。
  • is_float:检查参数是否为浮点数。
  • is_list:检查参数是否为列表。
  • is_dict:检查参数是否为字典。
  • is_set:检查参数是否为集合。
  • is_tuple:检查参数是否为元组。
  • is_not_none:检查参数是否不为None。
  • is_not_empty:检查参数是否不为空(对于字符串、列表、字典、集合等)。
  • is_allowed_value:检查参数是否在指定的允许值范围内。
  • max_length:检查参数的长度是否不超过指定的最大值。
  • min_length:检查参数的长度是否不小于指定的最小值。
  • is_substring:检查参数是否为指定字符串的子串。
  • is_subset:检查参数是否为指定集合的子集。
  • is_sublist:检查参数是否为指定列表的子列表。
  • contains_substring:检查参数是否包含指定字符串。
  • contains_subset:检查参数是否包含指定集合。
  • contains_sublist:检查参数是否包含指定列表。
  • is_file:检查参数是否为有效的文件;
  • is_dir:检查参数是否为有效的目录;
  • is_file_suffix:检查参数是否以指定文件后缀结尾。
  • is_similar_dict:检查参数是否与指定字典相似,如果key值相同,value类型相同,则判定为True,支持比对嵌套字典。
  • is_method:检查参数是否为可调用的方法(函数)。


除了以上内置验证器外,还可以使用 custom_validator 方法添加自定义验证器。


自定义验证器


from pyparamvalidate import ParameterValidator
def custom_check(value):
    return value % 2 == 0
@ParameterValidator("param").custom_validator(custom_check, "Value must be an even number")
def example_function(param):
    return param


更多使用方法


from pyparamvalidate.tests import test_param_validator


test_param_validatorParameterValidator 的测试文件,可点击 test_param_validator 参考更多使用方法。

目录
相关文章
|
5天前
|
Python
Python闭包函数和计时器
本文介绍了闭包函数的概念,它允许内部函数引用外部作用域的变量但无法修改它们。示例展示了如何使用闭包来封装函数。接着,文章讨论了如何在函数调用时添加开始和结束的打印语句,通过传递函数作为参数实现。然后,文章引入装饰器,通过闭包定义了一个`timer`装饰器,用于在函数执行前后打印消息。最后,给出了一个练习,实现了一个计算函数执行时间的装饰器,处理了带有参数的被装饰函数。
12 1
|
2天前
|
程序员 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,它可以简洁地实现函数的增强、扩展和重用。本文将深入探讨Python中装饰器的工作原理、常见应用场景以及如何自定义装饰器,帮助读者更好地理解和运用这一重要的编程概念。
|
3天前
|
数据采集 Python
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
|
3天前
|
数据采集 数据挖掘 Python
Python学习——函数,2024年最新手持4个大厂offer的我
Python学习——函数,2024年最新手持4个大厂offer的我
|
3天前
|
数据采集 数据挖掘 关系型数据库
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
|
3天前
|
存储 Java Shell
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案
|
3天前
|
Python
Python基础教程: math库常用函数(1),Python这些高端技术只有你还不知道
Python基础教程: math库常用函数(1),Python这些高端技术只有你还不知道
|
4天前
|
机器学习/深度学习 数据采集 自然语言处理
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
|
4天前
|
Python
Python 使用type()函数
【5月更文挑战第10天】
13 4
|
4天前
|
Python
Python使用isinstance()函数
【5月更文挑战第10天】Python使用isinstance()函数
9 2