Accept different types in python function? -


i have python function lot of major work on xml file.

when using function, want 2 options: either pass name of xml file, or pass pre-parsed elementtree instance.

i'd function able determine given in variable.

example:

def dolotsofxmlstuff(xmldata):     if (xmldata != # if xmldata not et instance):         xmldata = et.parse(xmldata)     # bunch of stuff     return stuff 

the app calling function may need call once, or may need call several times. calling several times , parsing xml each time hugely inefficient , unnecessary. creating whole class wrap 1 function seems bit overkill , end requiring code refactoring. example:

ourresults = dolotsofxmlstuff(myobject) 

would have become:

xmlobject = xmlprocessingobjectthathasonefunction("data.xml") ourresult = xmlobject.dolotsofxmlstuff() 

and if had run on lots of small files, class created each time, seems inefficient.

is there simple way detect type of variable coming in? know lot of pythoners "you shouldn't have check" here's 1 instance would.

in other strong-typed languages method overloading, that's not pythonic way of things...

the principle of "duck typing" shouldn't care specific type of object rather should check whether supports apis in you're interested.

in other words if object passed function through xmldata argument contains method or attribute indicative of elementtree that's been parsed use methods or attributes ... if doesn't have necessary attribute free pass through parsing.

so functions/methods/attributes of result et looking use? can use hasattr() check that. alternatively can wrap call such functionality try: ... except attributeerror: block.

personally think if not hasattr(...): bit cleaner. (if doesn't have attribut want, rebind name has been prepared, parsed, whatever need it).

this approach has advantages on isinstance() because allows users of functionality pass references objects in own classes have extended et through composition rather inheritance. in other words if wrap et object in own class, , expose necessary functionality should able pass reference s function , have treat object if "duck" if wasn't descendant of duck. if need feathers, bill, , webbed feet check 1 of , try use rest. may black box containing duck , may have provided holes through feet, duck-bill, , feathers accessible.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -