Check existence of members/methods

Nicolas Fleury nid_oizo at yahoo.com_remove_the_
Thu Sep 2 18:30:46 EDT 2004


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

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?

Regards,
Nicolas



More information about the Python-list mailing list