How do I give a decorator acces to the class of a decorated function

Chris Angelico rosuav at gmail.com
Wed Sep 4 11:03:35 EDT 2019


On Thu, Sep 5, 2019 at 12:23 AM Antoon Pardon <antoon.pardon at vub.be> wrote:
>
> What I am trying to do is the following.
>
> class MyClass (...) :
>     @register
>     def MyFunction(...)
>         ...
>
> What I would want is for the register decorator to somehow create/mutate
> class variable(s) of MyClass.
>
> Is that possible or do I have to rethink my approach?
>

At the time when the decorator runs, the class doesn't actually exist.
But if you're wrapping MyFunction (which appears to be a method), then
your wrapper function will receive  'self' as its first parameter, and
can access the class from that. Doesn't help at decoration time,
though.

ChrisA



More information about the Python-list mailing list