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

Rhodri James rhodri at kynesim.co.uk
Wed Sep 4 10:58:00 EDT 2019


On 04/09/2019 15:21, Antoon Pardon 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?

I can't see a way of doing that directly, but you could cheat by putting 
the "class variables" in a global dictionary?  And perhaps referencing 
that global from a class variable?  Something like:

my_class_registry = {}

class MyClass(...):
     MyClassRegistry = my_class_registry

     @register(my_class_registry)
     def MyFunction(...):
         ...

Or you may be able to achieve what you want with dir() and some careful 
naming?

-- 
Rhodri James *-* Kynesim Ltd



More information about the Python-list mailing list