Terry Reedy wrote:
Thanks for the review, Terry!
On 3/9/2012 5:10 PM, Ethan Furman wrote:
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.
If the class takes any arguments, I won't be able to create instances of it.
b. Put such tests in unit tests.
Always a good idea -- but this is the responsibility of the class author
(who may not be me ;).
c. Check the code object to see if the attribute will be created.
I have no idea how to do this -- pointers?
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 ;-).
Ouch. Can that be done in a cross-implementation way? Any pointers?
Still, I'm not sure I'd want to go this route, anyway, as it makes it
more difficult to get an actual class-wide mutable (rare though they are).
Thanks again for your feedback, I really appreciate it.
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list