prior
prior

Reputation: 518

Python Metaprogramming of Descriptors: How to add descriptor after class definition?

How do I associate a descriptor after a class has already been defined?

In a normal descriptor scenario I would just do this:

class X:
    d = Descriptor()

and then whenever Descriptor.__get__(self,obj,kls) is called, the second parameter is an instance of X and all is happy and wonderful.

But what if X is already defined like so:

class X: pass

How do I then add a descriptor after the fact (and have it function properly!)? All my attempts are not getting proper association to the class

I'm doing this cuz I have a bunch of attributes I want to add in a DRY manner, and I want them to be cached_properties (a descriptor I'm using to memoize the values for each of them)

Upvotes: 2

Views: 220

Answers (1)

Marcin
Marcin

Reputation: 49826

X.d = Descriptor()

That's all you need.

Upvotes: 3

Related Questions