Sometimes in my code there is a function that can take an argument in one of two ways. Something like:
def func(objname=None, objtype=None): if objname is not None and objtype is not None: raise ValueError("only 1 of the ways at a time") if objname is not None: obj = getObjByName(objname) elif objtype is not None: obj = getObjByType(objtype) else: raise ValueError("not given any of the ways") doStuffWithObj(obj)
Is there a more elegant way to do this? What if arg can come in one of three ways? If the types are different, I could do:
def func(objnameOrType): if type(objnameOrType) is str: getObjByName(objnameOrType) elif type(objnameOrType) is type: getObjByType(objnameOrType) else: raise ValueError("unk arg type: %s" % type(objnameOrType))
But what if it is not? This alternative seems silly:
def func(objnameOrType, isName=True): if isName: getObjByName(objnameOrType) else: getObjByType(objnameOrType)
then you should call it like func(mytype, isName=False) which is weird.
python design coding-style design-patterns
Claudiu
source share