stackoverflow question

Terry Reedy tjreedy at udel.edu
Sat Mar 10 00:16:32 CET 2012


On 3/9/2012 5:10 PM, Ethan Furman wrote:
> Hey all!
>
> I posted a question/answer on SO earlier, but there seems to be some
> confusion around either the question or the answer (judging from the
> comments).
>
> http://stackoverflow.com/q/9638921/208880
>
> If anyone here is willing to take a look at it and let me know if I did
> not write it well, I would appreciate the feedback
>
> Here's the question text:
> ------------------------
> I'm writing a metaclass to do some cool stuff, and part of its
> processing is to check that certain attributes exist when the class is
> created. Some of these are mutable, and would normally be set in
> `__init__`, but since `__init__` isn't run until the instance is created
> the metaclass won't know that the attribute *will* be created, and
> raises an error.
a. Create an instance and see if it has the attribute. Then delete it.
b. Put such tests in unit tests.
c. Check the code object to see if the attribute will be created.

> I could do something like:
>
> class Test(meta=Meta):
> mutable = None
> def __init__(self):
> self.mutable = list()
>
> But that isn't very elegant, and also violates DRY.

It works. It is a standard idiom for default values that are 
conditionally masked with an instance value.
>
> What I need is some way to have:
>
> class Test(metaclass=Meta):
> mutable = list()
>
> t1 = Test()
> t2 = Test()
> t1.mutable.append('one')
> t2.mutable.append('two')
> t1.mutable # prints ['one']
> t2.mutable # prints ['two']
>
> Any ideas on how this can be accomplished?

Rewrite the __init__ code object ;-).

-- 
Terry Jan Reedy




More information about the Python-list mailing list