(original) (raw)
On Thu, Mar 8, 2012 at 2:43 AM, Ethan Furman <ethan@stoneleaf.us> wrote:
>
> PJ Eby wrote:
>>
>> Short version: AddOns are things you can use to dynamically extend instances -- a bit like the "decorator" in "decorator pattern" (not to be confused with Python decorators). �Rather than synthesize a unique string as a dictionary key, I just used the AddOn classes themselves as keys. �This works fine for object instances, but gets hairy once classes come into play.
>
>
> Are you able to modify classes after class creation in Python 3? Without using a metaclass?
For ClassAddOns, it really doesn't matter; you can't remove them from the class they attach to. �Addons created after the class is finalized use a weakref dictionary to attach to their classes.
Now that I've gone back and looked at the code, the only reason that ClassAddOns even use the class \_\_dict\_\_ in the first place is because it's a convenient place to put them while the class is being built. �With only slightly hairier code, I could use an \_\_addons\_\_ dict in the class namespace while it's being built, but there'll then be a performance hit at look up time to do cls.\_\_dict\_\_\['\_\_addons\_\_'\]\[key\] instead of cls.\_\_dict\_\_\[key\].
Actually, now that I'm thinking about it, the non-modifiability of class dictionaries is actually a feature for this use case: if I make an \_\_addons\_\_ dict, that dict is mutable. �That means I'll have to move to string keys or have some sort of immutable dict type available... �;-) �(Either that, or do some other, more complex refactoring.)