简体   繁体   中英

Add an attribute to the module in which a Python decorator is running

I'd like to write a Python decorator that adds an attribute to the module in which a decorator is running, ie

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

should add an attribute attr to the module where whatever is found. I've tried writing the decorator procedure (defined in another file) as follows

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

but attr is added to the module where procedure is defined, not to the module where procedure runs. Is there some other way to do this?

Suppose you want to mark a function, such that some user of the module where it is defined will be able to know that it belongs to some category of functions. You could write a simple decorator like this:

def special(fn):
    globals().setdefault("__specials__", set()).add(fn)
    return fn

Then you can write a module that uses this decorator, like this:

"""Module 'has_specials'"""
def regular():
    return "meh"

@special
def important():
    return "wow!"

@special
def bigshot():
    return "HA"

This can then be used by another module like this:

import has_specials

if hasattr(has_specials, "__specials__"):
    for fn in has_specials.__specials__:
        print("%-20s: %s" % (fn.__name__, fn))

The code above will import the module, and list the special functions:

important           : <function important at 0x000002435FD51488>
bigshot             : <function bigshot at 0x000002435FD51510>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM