1

I'm trying to make a decorator in the form of a class because I have some very complicated functionality to store in it. But when I try to "call" the new decorator, it doesn't get passed self, at all.

class B:
    def __init__(self, other):
        self.other = other

    def __call__(self, *args, **kwargs):
        print('B.__call__', self, args, kwargs)
        self.other(*args, **kwargs)

class A:
    @B
    def m(self, *args, **kwargs):
        print('A.m', self, args, kwargs)

A().m()

Here's the output:

B.__call__ <__main__.B object at 0x10f43eeb8> () {}

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-7636a94e166d> in <module>
----> 1 A().m()

<ipython-input-19-3cd6266a4f37> in __call__(self, *args, **kwargs)
      5     def __call__(self, *args, **kwargs):
      6         print('B.__call__', self, args, kwargs)
----> 7         self.other(*args, **kwargs)
      8 
      9 class A:

TypeError: m() missing 1 required positional argument: 'self'

Am I making a mistake somewhere? Shouldn't self be put into *args in __call__? If not, what's wrong and how can I fix it?

Hameer Abbasi
  • 1,292
  • 1
  • 12
  • 34
  • This isn't calling an *instance* of `B`, but the *class* `B`, which is why `self` hasn't been defined yet, and thus is a missing positional arg. Try instantiating `B` like `b = B()` then the decorator is `@b` – C.Nivs Mar 21 '19 at 18:36
  • 1
    @C.Nivs No, that's wrong. The decorator works fine; the problem is that python doesn't create a bound method of `A().m` because `B` isn't a [descriptor](https://docs.python.org/3/glossary.html#term-descriptor). – Aran-Fey Mar 21 '19 at 18:40
  • @Aran-Fey yep just re-read the docs on that one, you're right – C.Nivs Mar 21 '19 at 18:40
  • @Aran-Fey If there's a way to create a bound method... That'd be great. I'm not that well-versed. :) – Hameer Abbasi Mar 21 '19 at 18:41
  • 1
    It's all there in the duplicate I linked. – Aran-Fey Mar 21 '19 at 18:50

0 Answers0