On Wed, Aug 15, 2018 at 9:09 AM, Chris Barker via Python-ideas
<python-ideas@python.org> wrote:
> no, it's not -- None is keyword, and just like any other keyword, it can't
> be re-bound. However, every other keyword I tried to rebind results in a
> generic:
>
> SyntaxError: invalid syntax
>
> (except None, True, and False)
>
> which I suppose is because while None is a keyword, it can be used pretty
> much anywhere any other name can be used (as opposed to say, def)

Yeah. That's the difference between "keywords that are syntactically
special" and "keywords that represent specific values". Most keywords
define syntax (you mention "def", and similarly "if", "global",
"import") or are operators ("and", "if", "is not"); the ones that
could theoretically be assigned to are defined in the grammar as forms
of atom.

atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [testlist_comp] ']' |
       '{' [dictorsetmaker] '}' |
       NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')

>>> ... = 1
  File "<stdin>", line 1
SyntaxError: can't assign to Ellipsis
>>> None = 2
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> True = 3
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> False = 4
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

Interestingly, even though the first example specifically says
"Ellipsis", it's perfectly acceptable to assign to that name:

>>> Ellipsis = 5
>>> print(Ellipsis)
5

Note also that the rules are slightly different in Python 2; True and
False are ordinary builtins, and "..." has meaning only inside a
subscript, so trying to assign to it makes as much sense as "<> = 1".

The special non-assignable status of None is therefore shared by three
other values; it's still special, but it's not unique. The same is
true of the behaviour of "if None:" - since it's a keyword and cannot
be assigned to, it will always have the same value, and since it's an
immutable value, it will always have the same truthiness, and since
the 'if' statement is always false, the bytecode can be optimized
away. So that's also not unique to None, but is behaviour shared by
other literals. (Only literals though - neither "if []:" nor "if {}:"
is optimized out, at least in CPython 3.7.)

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to