High schooler
High schooler

Reputation: 1680

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?

Upvotes: 6

Views: 2834

Answers (3)

Eevee
Eevee

Reputation: 48564

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 e.g. event registration, so that merely importing a module doesn't expect to need an app instance. A good example is their event subscriber.

Upvotes: 3

Evan
Evan

Reputation: 2357

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

Upvotes: 5

Christian Tapia
Christian Tapia

Reputation: 34166

Use

 if __name__ == "__main__":
    #code

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

Upvotes: 1

Related Questions