Using python decorator functions from another module

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

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

class SomeClass:
    pass

root = SomeClass

:

from othermodule import decorator

@decorator
class Someclass:
    pass

Any ideas?

+3
source share
4 answers

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

import sys
def decorator(cls):
    mod = __import__(cls.__module__)
    mod.root = cls
0
source

This already works:

from othermodule import decorator

@decorator
class Someclass:
    pass

Just enter othermodule.py:

def decorator(cls):
    #.... do something with cls
    return cls
+4
source

, - , , . , , . , , .

+4

Instead of a direct decorator, you can have a function that returns a decorator and accepts the global values โ€‹โ€‹of your module:

def decorator(globals):
    def dec(cls):
        globals.root = cls
        return cls
    return dec

@decorator(globals())
class SomeClass:
    ...
0
source

Source: https://habr.com/ru/post/1743801/


All Articles