Metaclass' __init__ Does not Initialize
Alex Martelli
aleax at aleax.it
Thu Nov 13 09:11:08 EST 2003
achan wrote:
> Thanks for all who responded!
>
> I did figure out the solution while thinking about how to get the values
> of
> __slots__ iteratively. That is, by using getattrib(obj, name, value).
> Therefore, the opposite way should be setattrib(obj, name). :-)
Wrong way 'round, as well as wrong spellings for the built-in functions:
getattr takes 2 arguments (the third one is optional and only used as the
default value when an attribute is not present), setattr takes 3.
> And for those who are puzzled why I insist on using __slots__, I'm using
> it to reduce errors and not for saving space, wink!
Right: you're using this feature for the wrong motivation, for a purpose
it's not meant nor designed to support, and in a way that's most likely
to reduce your coding productivity rather than enhancing it. Like the
vast majority of users of __slots__, btw; you're all looking for the kind
of "security blanket" that languages with declarations have made you used
to, and you're not gonna let a little detail such as the fact that you're
just not going to get it stand in your way.
If you're truly terrified that somebody, one day, might make a typo
and assign to an attribute that wasn't part of the class as you
designed it, you should:
1. relax. It's not any worse than the typo which some day will make
someone code "net=income+tax" where they MEANT "net=income-tax",
and no B&D language feture will let you catch THAT one anyway. So:
2. code unit-tests (ideally BEFORE the "production" code, feature by
feature). If your unit-tests are even halfways semidecent they'll
catch all the typos AND many more silly errors besides.
3. for occasional debug runs with super-thorough checks, if you still
feel the need for them, code a __setattr__ that vets each setting
for attributenames being in whatever set you want (you may then even
make that set into a dict, making each name optionally correspond
with a checkingpredicate that can be run on the value)
4. better than 3 (more general and far more useful), use DBC and turn
it on for those "super-nitpicky checks", that will catch MANY more
potential errors, not just typos on attributenames &c... and also
serve as useful documentation re invariants, preconditions, and
postconditions of your functions and methods.
For an implementation of [4], see, eg:
http://www.nongnu.org/pydbc/
http://www.pypackage.org/packages/python-dbc
Alex
More information about the Python-list
mailing list