Check existence of members/methods
Nicolas Fleury
nid_oizo at yahoo.com_removethe_
Sat Sep 4 17:17:21 EDT 2004
Alex Martelli wrote:
> try: meth = object.setXmlFilename
> except AttributeError: meth = lambda x: setattr(object,'xmlFilename',x)
> meth(currentFillename)
>
> This doesn't assume that object.xmlFilename must already exist before
> you can set it, which IS implied by your code here quoted -- it just
> seems a slightly weird condition to me.
In my case, a xml parser/saving creating objects corresponding to
elements and vice-versa, forcing the existence of members before setting
them makes the code more readable (and avoid a lot of errors). I agree
it would be a weird restriction in other situations.
> I personally prefer the try/except/else variant:
>
> try: meth = object.setXmlFilename
> except AttributeError: object.xmlFilename = x
> else: meth(currentFillename)
>
> it seems way simpler to me. However, if you think of objects lacking a
> setter method as weird and exceptional ones, I see why this might seem
> backwards. Personally, I consider setter methods the anomaly (it's
> exactly to avoid them that we have property...:-) but I do understand
> they're frequently used. If I often had to fight with objects full of
> getThis, setThat methods I'd wrap them into a generic wrapper with a
> __setattr__ and __getattr__ to be able to use attribute get and set as
> common sense and decency require, e.g, something like....:
Actually, I prefer the "hasattr" solution. I'm thinking of removing the
setter functionality from the parser. If some class needs to do
specific stuff when a member is updated, as you said, the built-in
function property can still be used.
Regards,
Nicolas
More information about the Python-list
mailing list