Re: Bizarre behavior with mutable default arguments



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
.



Relevant Pages

  • Re: Anonymus functions revisited : tuple actions
    ... Checks locals, globals, and builtins for the varable name. ... def isa: ... otherwise return the varable obj. ...
    (comp.lang.python)
  • Re: PEP-343 - Context Managment variant
    ... > def Synhronised: ... 'globals' means the module global namespace as returned by globals. ... We must declare local vars, to which we wish assign in "global" ... You cannot rebind enclosed local variables, ...
    (comp.lang.python)
  • Re: singletons
    ... this is a common approach in python. ... The one drawback to this is that it could require lots of globals ... def something: ...
    (comp.lang.python)
  • Re: undo a dictionary
    ...     for key, value in dd.items: ... globals() as the default names space, ... def undict(self, dict): ...
    (comp.lang.python)
  • Re: Problem with exec
    ... would look up its globals in namespace, that might be an interesting concept ... The 'thunk' function, defined below, turns a function into code that can be ... def simple_assigns: ...
    (comp.lang.python)