Implicit lists

Max M maxm at mxm.dk
Fri Jan 31 09:54:19 CET 2003


Erik Max Francis wrote:

> In dynamically-typed languages like Python, overloading functions (which
> is I presume the crux of where you're doing this test) based on type
> usually isn't a great idea.  Usually it's better to have two
> functions/methods instead.


This is a bad idea in many cases.

Very often you want a function that has this interface:

     def getWhere(options): # options is a list
         "generates query"


it could generate a query like:

     SELECT * FROM table WHERE option='spam' or option='ni'

So the easiest way to do this is to write a function like this:

     def getWhere(options):
         return 'SELECT * FROM table WHERE %s' % ' or '.join(
                ['option=%s' for opt in options])

But frequently you will only call getWhere() with one argument. So 
instead of having to call it like:

     def getWhere(['spam']):
         "generates query"

You want to call it like

     def getWhere('spam'):
         "generates query"

If you do not have polymorphic interfaces you will need to typecheck 
your argument everytime you call the function:

if type(options) == type(''): # I *know* this sucks!
     getWhere([options])
else:
     getWhere(options)

If you want to make 2 functions:

     def getWhereByOne('spam'):
         "generates query"

     def getWhere(['spam']):
         "generates query"

You will need to check if the argument is a list or a string in all the 
code wich calls one of the function.

if type(options) == type(''):
     getWhereByOne(options)
else:
     getWhere(options)

This is no better than the first option.

So the sane approach is to do the check inside the function:

     def getWhere(options):
         if type(options) == type(''): # I *know* this sucks!
             options = [options]
         return 'SELECT * FROM table WHERE %s' % ' or '.join(
                ['option=%s' for opt in options])

This will lead to far the most simple use of the function.

-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list