python - 向运行 Python 装饰器的模块添加属性
问题描述
我想编写一个 Python 装饰器,它向正在运行装饰器的模块添加一个属性,即
@procedure
def whatever(arg1, arg2):
# do things
return
attr
应该向找到的模块添加一个属性whatever
。我尝试编写装饰器procedure
(在另一个文件中定义)如下
def procedure(fn):
global attr
attr = SomeClass()
return fn
但attr
被添加到procedure
定义的模块,而不是procedure
运行的模块。还有其他方法可以做到这一点吗?
解决方案
假设您要标记一个函数,以便定义它的模块的某些用户能够知道它属于某个函数类别。你可以像这样写一个简单的装饰器:
def special(fn):
globals().setdefault("__specials__", set()).add(fn)
return fn
然后你可以编写一个使用这个装饰器的模块,像这样:
"""Module 'has_specials'"""
def regular():
return "meh"
@special
def important():
return "wow!"
@special
def bigshot():
return "HA"
然后可以由另一个模块使用,如下所示:
import has_specials
if hasattr(has_specials, "__specials__"):
for fn in has_specials.__specials__:
print("%-20s: %s" % (fn.__name__, fn))
上面的代码将导入模块,并列出special
函数:
important : <function important at 0x000002435FD51488>
bigshot : <function bigshot at 0x000002435FD51510>
推荐阅读
- linux - 从 rcu 列表中添加和查找 rcu 节点
- jquery - Knockout BeforeRemove 返回 textNode 而不是 elementNode
- excel - source 当前评估为错误 excel
- html - 让 DIV 与 SVG 重叠
- sql - 与 SQL Server 中的临时表相比,为什么 CTE(公用表表达式)在某些情况下会减慢查询速度
- dc.js - 使用 dc.selectmenu 过滤多键维度
- cloudera - 可能的身份验证问题导致的集群损坏
- ruby-on-rails - rails 从公共文件夹下载文件
- java - 元组 Java 类似于 OPL 中的元组
- security - 如何从不受信任的工作节点中保护 docker swarm 管理器?