Implicit lists
Beni Cherniavsky
cben at techunix.technion.ac.il
Mon Feb 3 17:57:30 EST 2003
On 2003-01-31, Mel Wilson wrote:
> In article <XOq_9.48875$Hl6.6191395 at news010.worldonline.dk>,
> Max M <maxm at mxm.dk> wrote:
> >
> >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"
>
Since you only need one such "magic" argument and it's the last argument,
let me borrow Guido's time machine::
def getWhere(*foods):
return list(foods) # insert useful code here
getWhere('spam')
getWhere('spam', 'eggs')
getWhere(*foodlist)
The point is to "refuse the temptation to guess". In my experience,
any [1]_ attempt to dispatch on the argument being a sequence / atom
always *reduces* the utility of the function. A single interface is
clearest. One of the interfaces must be written differently so that
your intent is unambiguous. If you are lucky, you get a chance to
choose which of them should get the simpler syntax (which is the idea
above) but then the other suffers. (Or have two different
functions/keywords as someone suggested).
.. [1] The only exception is when you build a complete "mini-language"
using the builtin types (lists, strings, etc.) for the
structure. It's a nice LISPish thing to do (but applicable in
Python two, actually lists + dicts + tuples give you lot of
flexibility). However, if you do such a thing, always remember
to provide a "quoting" syntax which allows to embed any data
structure without it being auto-interpreted...
> Then there is the possibility for confusion. This
> Do-What-I-Mean feature has already injected lumps into base
> Python:
>
> >>> print '%s' % 1
> 1
> >>> print '%s' % (1,2)
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: not all arguments converted
> >>>
>
> by giving a possibly unwanted, or unwonted, meaning to
> tuples vs. other types in doing string modulus. (Strictly,
> the unwonted meaning is being given to the other types, by
> relaxing the requirement that '%' take a tuple. Either way
> though, forget what you're doing and KABOOM!)
>
Sure, this is a wart. Since writing singleton tuples is awkward [2]_,
I suggest adding a __div__ method to strings that will accept a single
arg and slowly deprecating the __mod__ exception for a single arg::
"%d" / 1 # My suggestion.
"%d,%d" % (1,2) # Stays as now.
"%d" % (1,) # Perfectly legal, should stay (but will be
# rarely used, mainly when the tuple is
# computed).
"%d" % 1 # To be deprecated.
--
Beni Cherniavsky <cben at tx.technion.ac.il>
My first thought upon hearing the company name "22 Design":
That's not a valid identifier (starts with a digit)!
More information about the Python-list
mailing list