python - 也可以用作独立函数的 Python 装饰器
问题描述
我对装饰器很陌生,我正在尝试构建一个带有参数的装饰器,该参数既可以作为装饰器,也可以作为独立函数使用。基本思想是在不满足某些条件时引发错误。例子:
ensure_condition("fail") # exception should be raised
ensure_condition("pass") # nothing should happen
@ensure_condition("fail") # check condition before every `func` call
def f1():
return 1
我想过这样做:
def ensure_condition(arg: str):
if not _validate(arg):
raise Exception("failed")
def ensure_condition_decorator(f = lambda *_: None):
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
return ensure_condition_decorator
但是上面的结果在函数被声明(不仅仅是执行)_validate
时也会被调用。f1
还有其他想法吗?
谢谢!
解决方案
推荐阅读
- excel - 如何在 24 小时内计算(总结)适当的百分比(不超过 100%)
- java - Jackson-xml 不解析嵌套对象
- json - 嵌套 JSON 的叶子作为 JS 中的完整数据
- c# - 使用 Windows 标识安全地保存用户数据
- c++ - 来自枚举值的 C++ decltype
- node.js - 尽管存在数据,但在 GraphQL 查询中日期字段返回为空
- angular - 为什么 Firestore 数据检索适用于 ng-serve 版本但在 ng-build 版本中失败
- java - 使用 java 连接到 Microsoft SQL 服务器的 JDBC
- c++ - 如何转换不同类型的迭代器
- ruby - 如何运行 ruby 脚本来解压缩文件?