Check existence of members/methods

Nicolas Fleury nid_oizo at yahoo.com_remove_the_
Thu Sep 2 18:33:55 EDT 2004


Nicolas Fleury wrote:

> Hi everyone,
>     I'm wondering what is the easiest/cleanest way to look for existence 
> of available methods/members.
> 
> For example, in parsing a xml file, created objects can define a 
> setXmlFilename function or a xmlFilename member to get the filename they 
> are from.
> 
> Right now I have the following code:
> 
> try: object.setXmlFilename
> except:
>     try: object.xmlFilename
>     except: pass
>     else: object.xmlFilename = currentFilename
> else: object.setXmlFilename(currentFilename)
> 
> But it looks a bit wierd, since it's like a "if" with the false 
> consequence presented first.  I wonder if there is, and if there should 
> be a better way to do it.  I could also do the following:
> 
> 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

In fact, it's even more ugly:

def exists(obj, name):
     try: eval("obj." + name)
     except: return True
     return False

if exists(object, "setXmlFilename"):
     object.setXmlFilename(currentFilename)
elif exists(object, "xmlFilename"):
     object.xmlFilename = currentFilename



More information about the Python-list mailing list