2

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?

mlstudent
  • 948
  • 2
  • 15
  • 30
  • 1
    Can you give an example of what you are trying to do ? – hivert Feb 16 '14 at 08:08
  • possible duplicate of [python decorators with parameters](http://stackoverflow.com/questions/5929107/python-decorators-with-parameters) – hivert Feb 16 '14 at 08:10

1 Answers1

1

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).

Stan Prokop
  • 5,579
  • 3
  • 25
  • 29
  • To clarify, this would require that in every main program on the client side, I would have to add the line factory = DecoratorFactory(some arguments here), right? Could I set a default in case the client doesn't specify it? – mlstudent Feb 17 '14 at 03:10
  • Right. You can create a predefined factory in some module in its global scope with methods to change its variable or client can create his own module with his own global factory. – Stan Prokop Feb 17 '14 at 05:59
  • Where would I do that? Right now, the library I'm working on has a bunch of modules that have function definitions, and then one module that defines this factory class. – mlstudent Feb 19 '14 at 08:11
  • Either in the module with factory definition or separate module. Or root __init__. Or elsewhere. Choose what suits you and/or your target user. – Stan Prokop Feb 22 '14 at 07:17