The binding operator, and what gets bound to what (was: About Modifying Globals)
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Dec 5 04:53:49 EST 2014
Ben Finney wrote:
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>
>> LJ wrote:
>>
>> > def gt(l):
>> > a["1"] = a["1"] | set([l])
>>
>> The difference between this example and your second one:
>>
>> > def gt2(l):
>> > b=b+l
>>
>>
>> is that the second is a "binding operation" and the first is not.
>
> I disagree; they're both binding operations (and they both use the
> binding operator ‘=’ to express this).
Define "operator" :-)
In Python terms, operators include + - * etc. They return a result, and are
implemented by a special __dunder__ method. (Sometimes by two dunder
methods, e.g. __add__ and method __radd__.)
By this definition, = is not an operator. And indeed, the Python docs don't
list = as an operator:
https://docs.python.org/2/reference/lexical_analysis.html#operators
but it is listed as a delimiter:
https://docs.python.org/2/reference/lexical_analysis.html#delimiters
That's why I was careful to use the term "binding operation" and
avoid "operator", although I admit that was pretty subtle :-)
As for the rest of your comments:
> The difference between the two is: what reference is being bound?
I don't think we disagree, we merely have a different emphasis. The rules
for assignments in Python are a bit complicated, and the official language
used is often different from what we say informally:
https://docs.python.org/2/reference/simple_stmts.html#assignment-statements
Of course you are right that other assignment statements bind a value to a
reference of some sort:
spam.method().attribute['key'].thingy[0] = eggs
but *not for the purpose of deciding what is a local variable*. That was the
point I was emphasising.
The docs referenced above say:
Assignment of an object to a single target is recursively
defined as follows.
If the target is an identifier (name):
If the name does not occur in a global statement in the
current code block: the name is bound to the object in
the current local namespace.
Otherwise: the name is bound to the object in the current
global namespace.
which is a little less than clear, but basically it means that assignments
of the form:
name = something
force name to be a local variable unless it is explicitly declared global.
More information here:
https://docs.python.org/2/reference/simple_stmts.html#the-global-statement
Oh, I learned something new: strictly speaking, this is implementation-
dependent and not guaranteed to work in the future!
def func():
global math
import math
--
Steven
More information about the Python-list
mailing list