lambda in list comprehension acting funny

Hans Mulder hansmu at
Fri Jul 13 19:53:16 CEST 2012

On 13/07/12 18:12:40, Prasad, Ramit wrote:
>> 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.

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.

Hope this helps,

-- HansM

More information about the Python-list mailing list