lambda in list comprehension acting funny

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Jul 13 14:06:31 EDT 2012


> >> VERBOSE = True
> >>
> >> def function(arg):
> >>     if VERBOSE:
> >>        print("calling function with arg %r" % arg)
> >>     process(arg)
> >>
> >> def caller():
> >>     VERBOSE = False
> >>     function(1)
> >>
> >> ---------------------------------------------
> >> Python semantics: function sees VERBOSE False
> >> Haskell semantics: function sees VERBOSE True
> 
> >>>> def caller():
> > ...     VERBOSE = False
> > ...     function(1)
> >>>> def function(arg):
> > ...     if VERBOSE:
> > ...        print("calling function with arg %r" % arg)
> > ...
> >>>> VERBOSE = True
> >>>> caller()
> > calling function with arg 1
> >
> > I might be being OCD, but caller needs `global VERBOSE` for that to
> > work as you explain.
> 
> That would be quite different from what Rusi is after.
> 
> If you add `global VERBOSE` to `caller`, then there is only one
> variable named `VERBOSE` and what `function` does, depends on
> the most recent assignment to that variable.
> 
> If you remove your `global VERBOSE`, then there are two
> variables by that name, one global and one local to `caller`.
> In that case, there is the question of which one `function`
> will use.
>

But that is not what Rusi writes.
"Python semantics: function sees VERBOSE False" <- function
will not see False without the use of global. 

> The function `function` refers to a variable `VERBOSE` that
> isn't local.  In some programming langauages, the interpreter
> would then scan the call stack at run-time, looking for a scope
> where that name is defined.  It would find the local one in
> `caller`.  This is known as "dynamic binding".
> 
> Other interpreters use the `VERBOSE` that was in scope at
> the point in the program text where `function` was defined.
> In this case, that would be the global one.  This is called
> "lexical binding".
> 
> Some programming languages allow you to indicate on a per-
> variable basis whether you want dynamic or lexical binding.
> 
> Python is firmly in the lexical camp.  Dynamic binding is not
> available in Python, and never will be.

True and a good explanation, but not what I understood
Rusi to mean.

Ramit



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list