简体   繁体   中英

How to make Python Decorator NOT run when imported

I've decorated a method in Python. And when I import the module that contains the method, the decorator autoruns.

I realize that this is how decorators were made however Is there a way to have decorators NOT do this?

It sounds like what you want to do is to choose what decorator to apply at run time. Something like this might work:

to_decorate = []

def decorate_later(func):
    to_decorate.append(func)
    return func

@decorate_later
def do_stuff(*args, **kw):
    print('I am doing stuff')
@decorate_later
def do_more_stuff(*args, **kw):
    print('Even more stuff')

def apply_decorator(decorator):
    for func in to_decorate:
        globals()[func.func_name] = decorator(func)

Then you can import the module and all the functions will be defined as normal. decorate_later returns the original function unmodified. You can call apply_decorator() to apply a specified decorator to all of the functions in the module that were registered by @decorate_later

This is exactly what the venusian library does; you define your decorators according to their API, but the actual behavior isn't triggered until you do a "scan" of the containing module or package.

You don't even need to have a global app object to use venusian decorators; you can pass in the app object as part of the scan, and it'll get passed along to the decorator implementations. So, for example, the same functions can be shared among multiple owners with only a single decorator, just by doing more than one scan.

This is what the Pyramid web framework uses for eg event registration, so that merely importing a module doesn't expect to need an app instance. A good example is their event subscriber .

Use

 if __name__ == "__main__":
    #code

in the file, where code is all outside a method or class ( that runs when you import it).

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