Doug W
Doug W

Reputation: 173

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?

Upvotes: 17

Views: 25718

Answers (4)

Duncan
Duncan

Reputation: 95722

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

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

Upvotes: 3

Mad Physicist
Mad Physicist

Reputation: 114478

Instead of a direct decorator, you can have a function that returns a decorator and accepts the globals of your module:

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

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

Upvotes: 0

Mike Graham
Mike Graham

Reputation: 76753

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.

Upvotes: 7

nosklo
nosklo

Reputation: 223092

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

Upvotes: 11

Related Questions