Method acting on arguements passed

Duncan Booth duncan.booth at invalid.invalid
Fri May 5 14:47:01 CEST 2006


Panos Laganakos wrote:

> I want a class method to take action depending on the type of the
> arguement passed to it.
> 
> ie:
> getBook(id) # get the book by ID
> getBook(name) # get the book by name
> ...
> 
> Other languages use the term function/method overloading to cope with
> this. And when I googled about it seems that GvR is testing it for 3.0
> inclusion or so.
> 
> I was thinking of right after the function declaration check for the
> parameter passed by isinstance() or type() and use if..elif..else to
> act.
> 
> Is this the pythonic way/best practice to apply here?
> 
I think the most Pythonic way is probably to have separate methods. You 
presumably know at the point when you are calling getBook whether you have 
an id or a name. So be explicit:

  getBookById(id)
  getBookByName(name)

This has the advantage that id and name could both be strings and the code 
will still do the right thing. No amount of function overloading will 
resolve arguments which have the same type but mean different things.

Another reasonable way to go is to use keyword arguments:

  getBook(id=id)
  getBook(name=name)

which keeps down the number of different methods but could be confusing as 
you have mutually exclusive keyword arguments.

Another option you might have here, if getBook does a lookup in a 
dictionary, or database query, is simply to index the books by both id and 
name. Then the definition might be:

  def getBook(self, idorname):
     return self._books[idorname]

and there is still no typechecking.

If you do feel you need typechecking, consider pulling it out into a 
separate method so you are actually testing for the meaning of the 
parameter rather than explicitly testing its type everywhere:

  def getBook(self, idorname):
     if self.isvalidid(idorname):
          ....
     elif self.isvalidname(idorname):
          ....
     else:
         raise Oops()




More information about the Python-list mailing list