Bizarre behavior with mutable default arguments
bukzor
workitharder at gmail.com
Sun Dec 30 15:41:57 EST 2007
On Dec 30, 12:32 pm, Istvan Albert <istvan.alb... at gmail.com> wrote:
> On Dec 30, 11:26 am, George Sakkis <george.sak... at gmail.com> wrote:
>
> > I'm with you on this one; IMHO it's one of the relatively few language
> > design missteps of Python, favoring the rare case as the default
> > instead of the common one.
>
> George, you pointed this out this link in a different thread
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877
>
> how would you rewrite the code below if you could not use mutable
> default arguments (global variables not accepted)? Maybe there is a
> way, but I can't think of it as of now.
>
> ---------------------------------------
>
> def blocks(s, start, end):
> def classify(c, ingroup=[0]):
> klass = c==start and 2 or c==end and 3 or ingroup[0]
> ingroup[0] = klass==1 or klass==2
> return klass
> return [tuple(g) for k, g in groupby(s, classify) if k == 1]
>
> print blocks('the {quick} brown {fox} jumped', start='{', end='}')
Extremely simple
def blocks(s, start, end):
ingroup=[0]
def classify(c):
klass = c==start and 2 or c==end and 3 or ingroup[0]
ingroup[0] = klass==1 or klass==2
return klass
return [tuple(g) for k, g in groupby(s, classify) if k == 1]
print blocks('the {quick} brown {fox} jumped', start='{', end='}')
No globals, as you specified. BTW, it's silly not to 'allow' globals
when they're called for, otherwise we wouldn't need the 'global'
keyword.
--Buck
More information about the Python-list
mailing list