Check existence of members/methods

Alex Martelli aleaxit at yahoo.com
Sat Sep 4 11:00:31 CEST 2004


Nicolas Fleury <nid_oizo at yahoo.com_remove_the_> wrote:
   ...
> def noraise(expressionString):
>      try: eval(expressionString)
>      except: return True
>      return False
> 
> if noraise("object.setXmlFilename"):
>      object.setXmlFilename(currentFilename)
> elif noraise("object.xmlFilename"):
>      object.xmlFilename = currentFilename
> 
> But it puts code in strings, which I feel less natural.  What do you 
> think about it?  Have I miss a better solution or is there something for
> that in the language?


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.

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....:

class MakeSensible:
    def __init__(self, obj): self.__dict__['obj'] = obj
    def __getattr__(self, name):
         methname = 'get' + name[0].uppercase() + name[:1]
         return getattr(self.obj,methname)()
    def __setattr__(self, name, value):
         methname = 'set' + name[0].uppercase() + name[:1]
         return getattr(self.obj,methname)(value)

(or, you could build all the needed properties at wrapping time, but
it's unclear if that would be an advantage in performance and it would
surely take a bit more code!-).  Having made the object sensible once
and for all, thanks to this wrapper, you wouldn't need to thread
carefully throughout the rest of your application...


Alex



More information about the Python-list mailing list