Re: Bizarre behavior with mutable default arguments
- From: bukzor <workitharder@xxxxxxxxx>
- Date: Sun, 30 Dec 2007 12:41:57 -0800 (PST)
On Dec 30, 12:32 pm, Istvan Albert <istvan.alb...@xxxxxxxxx> wrote:
On Dec 30, 11:26 am, George Sakkis <george.sak...@xxxxxxxxx> 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
.
- Follow-Ups:
- Re: Bizarre behavior with mutable default arguments
- From: Steven D'Aprano
- Re: Bizarre behavior with mutable default arguments
- From: Istvan Albert
- Re: Bizarre behavior with mutable default arguments
- References:
- Bizarre behavior with mutable default arguments
- From: bukzor
- Re: Bizarre behavior with mutable default arguments
- From: "Martin v. Löwis"
- Re: Bizarre behavior with mutable default arguments
- From: Istvan Albert
- Re: Bizarre behavior with mutable default arguments
- From: bukzor
- Re: Bizarre behavior with mutable default arguments
- From: George Sakkis
- Re: Bizarre behavior with mutable default arguments
- From: Istvan Albert
- Bizarre behavior with mutable default arguments
- Prev by Date: Re: Tab indentions on different platforms?
- Next by Date: Re: Sub-classing unicode: getting the unicode value
- Previous by thread: Re: Bizarre behavior with mutable default arguments
- Next by thread: Re: Bizarre behavior with mutable default arguments
- Index(es):
Relevant Pages
|