Search code examples
pythondecorator

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?


Solution

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

    def decorator(cls):
        mod = __import__(cls.__module__)
        mod.root = cls