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?
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.
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.
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.
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.
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
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.
This is a bit hacky, but try this in othermodule.py
:
import sys
def decorator(cls):
mod = __import__(cls.__module__)
mod.root = cls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With