0

I'm really at a loss here. I need to pass arguments to the wrapper; these arguments change with runtime. Any idea how this could be solved using wrappers for classes?

def wrapper(x=None):
    def decorate(cls):
        def fct(self):
            print('wrapper argument is: %s' % x)
        cls.fct = fct
        return cls
    return decorate

a = 'first'


@wrapper(x=a)
class Test():
    pass

test = Test()
test.fct()  # Prints: first

a = 'second'
test.fct()   # Prints: first (instead of second)
Croneter
  • 3
  • 1
  • Here's a good answer: http://stackoverflow.com/a/15148557/1647656 – Alex Guerra May 12 '17 at 15:57
  • Thanks for your answer. I don't quite understand yet - even passing a mutable object like a list does not work (a = ['first'] @wrapper(x=a), ...). How would I go about to solve this issue? – Croneter May 14 '17 at 14:35

1 Answers1

0

I can't put code in a comment, so here's how you'd do it.

def wrapper(x=None):
    def decorate(cls):
        def fct(self):
            print('wrapper argument is: %s' % x[0])
        cls.fct = fct
        return cls
    return decorate

a = ['first']


@wrapper(x=a)
class Test():
    pass

test = Test()
test.fct()  # Prints: first

a[0] = 'second'
test.fct()   # Prints: second

The key is that strings are immutable, whereas lists are mutable. When you pass in a string, it's basically copied. When you pass in a list, you're sort of passing a reference to the original list, which is itself mutable.

Alex Guerra
  • 2,556
  • 3
  • 18
  • 24