Question

I have a memoizer decorator class in a library, as such:

class memoizer(object):
        def __init__(self, f):
            "some code here"
        def __call__(self, *args, **kwargs):
            "some code here"

When I use it for functions in the library, I use @memoizer. However, I'd like to have the client (ie the programmer using the library) initialize the memoization class from outside the library with some arguments so that it holds for all uses of the decorator used in the client program. Particularly, this particular memoization class saves the results to a file, and I want the client to be able to specify how much memory the files can take. Is this possible?

Was it helpful?

Solution

You can achieve this using decorator factory:

class DecoratorFactory(object):
    def __init__(self, value):
        self._value = value

    def decorator(self, function):
        def wrapper(*args, **kwargs):
            print(self._value)
            return function(*args, **kwargs)
        return wrapper

factory = DecoratorFactory("shared between all decorators")

@factory.decorator
def dummy1():
    print("dummy1")

@factory.decorator    
def dummy2():
    print("dummy2")

# prints:
# shared between all decorators
# dummy1
dummy1()

# prints:
# shared between all decorators
# dummy2
dummy2()

If you don't like factories you can create global variables within some module and set them before usage of our decorators (not nice solution, IMO factory is more clean).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top