Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python decorator functions from a different module

I want to use a function from another module as a decorator, but I need it to manipulate the current module's global namespace.

For example, I want to be able to go from this:

class SomeClass:
    pass

root = SomeClass

to this:

from othermodule import decorator

@decorator
class Someclass:
    pass

Any ideas?

like image 828
Doug W Avatar asked May 03 '10 10:05

Doug W


People also ask

Can you have multiple decorators Python?

Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python.

Are decorators Pythonic?

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.

Does decorator order matter Python?

The broader answer is that it depends on what each of the decorators are doing. You need to think about the flow of your program and whether it would make logical sense for one to come before the other. Show activity on this post. You should do it like below.

When would you use a function decorator?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.


3 Answers

That already works:

from othermodule import decorator

@decorator
class Someclass:
    pass

Just put in othermodule.py:

def decorator(cls):
    #.... do something with cls
    return cls
like image 77
nosklo Avatar answered Oct 14 '22 11:10

nosklo


Having a decorator modify the global namespace if any module, let alone another module, is bad and never necessary. Code that mutates far-away globals is difficult to read and maintain. You should definitely consider modifying your design to avoid mutable global state and especially implicit assignment.

like image 30
Mike Graham Avatar answered Oct 14 '22 10:10

Mike Graham


This is a bit hacky, but try this in othermodule.py:

import sys
def decorator(cls):
    mod = __import__(cls.__module__)
    mod.root = cls
like image 29
Duncan Avatar answered Oct 14 '22 11:10

Duncan