向运行Python装饰程序的模块添加属性

2024-06-08 23:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个Python decorator,它向运行decorator的模块添加一个属性,即

@procedure
def whatever(arg1, arg2):
    # do things
    return

应该向找到whatever的模块添加属性attr。我试着编写decoratorprocedure(在另一个文件中定义),如下所示

def procedure(fn):
    global attr
    attr = SomeClass()
    return fn

但是attr被添加到定义了procedure的模块中,而不是添加到运行procedure的模块中。还有别的办法吗


Tags: 模块return属性定义defdecoratordofn
1条回答
网友
1楼 · 发布于 2024-06-08 23:39:59

假设您想标记一个函数,这样定义它的模块的某些用户将能够知道它属于某类函数。您可以编写一个简单的装饰器,如下所示:

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>

相关问题 更多 >