Note that there are some explanatory texts on larger screens.

plurals
  1. POAccept different types in python function?
    primarykey
    data
    text
    <p>I have a Python function that does a lot of major work on an XML file.</p> <p>When using this function, I want two options: either pass it the name of an XML file, or pass it a pre-parsed ElementTree instance.</p> <p>I'd like the function to be able to determine what it was given in its variable. </p> <p>Example:</p> <pre><code>def doLotsOfXmlStuff(xmlData): if (xmlData != # if xmlData is not ET instance): xmlData = ET.parse(xmlData) # do a bunch of stuff return stuff </code></pre> <p>The app calling this function may need to call it just once, or it may need to call it several times. Calling it several times and parsing the XML each time is hugely inefficient and unnecessary. Creating a whole class just to wrap this one function seems a bit overkill and would end up requiring some code refactoring. For example:</p> <pre><code>ourResults = doLotsOfXmlStuff(myObject) </code></pre> <p>would have to become:</p> <pre><code>xmlObject = XMLProcessingObjectThatHasOneFunction("data.xml") ourResult = xmlObject.doLotsOfXmlStuff() </code></pre> <p>And if I had to run this on lots of small files, a class would be created each time, which seems inefficient. </p> <p>Is there a simple way to simply detect the type of the variable coming in? I know a lot of Pythoners will say "you shouldn't have to check" but here's one good instance where you would. </p> <p>In other strong-typed languages I could do this with method overloading, but that's obviously not the Pythonic way of things...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload