Re: Check existence of members/methods

From: Nicolas Fleury (nid_oizo_at_yahoo.com_remove_the_)
Date: 09/03/04


Date: Thu, 02 Sep 2004 18:33:55 -0400

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



Relevant Pages

  • newb comment request
    ... So i wrote my first module which reads this pickled file and writes ... who creates the tables according to details found in the XML file). ... def ExtractFieldNamesFromData: ... NoneValues, sampleValue] ...
    (comp.lang.python)
  • Re: tuples within tuples
    ... Actually i'm parsing an xml file using pyrxp, ... (tagName, attributes, list_of_children, spare) ... def visitDefault: ... then when you want to use it you subclass Visitor adding appropriate ...
    (comp.lang.python)
  • Re: Finding Line numbers of HTML file
    ... I am cross posting the same to grab your attention at pyparsing forums ... This crude verifier turned up no mismatches when parsing the Yahoo ... In your getlinenos function, it is not necessary to call ... def getlinenos: ...
    (comp.lang.python)
  • Re: Advice for editing xml file using ElementTree and wxPython
    ... The trick is to keep a reference to the actual ElementTree objects ... If the XML file is very large you may have performance issues since ... root = tree.AddRoot ... def add: ...
    (comp.lang.python)
  • Re: Advice for editing xml file using ElementTree and wxPython
    ... The trick is to keep a reference to the actual ElementTree objects ... If the XML file is very large you may have performance issues since ... root = tree.AddRoot ... def add: ...
    (comp.lang.python)