[Python-ideas] relaxing keyword usage restrictions
Terry Reedy
tjreedy at udel.edu
Fri Sep 9 18:38:39 CEST 2011
On 9/9/2011 4:11 AM, Paul Moore wrote:
> On 9 September 2011 08:48, Terry Reedy<tjreedy at udel.edu> wrote:
>>> One cannot however write readable code such as the following:
>>> if yield> principal:
>>> return = yield - principal
>>
>> Funny you should choose that example. With a slight change
>> myreturn = yield - principal
>> it is legal syntax today with 'yield' interpreted as a keyword. So it cannot
>> be interpreted as an identifier without making Python grammar ambiguous and
>> unparseable with its current parser.
>
> Here is some currently legal syntax:
>
> globals()['return'] = lambda x:x
> def f():
> return(12)
>
> print(f())
>
> Currently, that prints 12. If keywords are allowed as variable names,
> presumably it should produce 'None'? Or should we break the semantics
> of globals()? Or what?
C now has a very similar problem.
(According to Eli Bendersky) The C statememnt
f(a);
can either be a function call (presumably with side-effects) or a
declaration that a is a variable of type f.
> And given that the globals() line could be arbitrarily far away from
> the definition of f(), the parser would need arbitrary lookbehind. And
> lookahead, as the globals() line could be in a function defined after
> f but called before it.
The C typedef ambiguity has to be resolved according to whether there is
or is not a typedef for f in effect at that particular spot. This can
even change within a statement. That determination requires arbitrary
lookbehind, including the effect of #include directives.
For Python, the runtime statements
from module import * # or somewhat equivalently
for k,v in parse_config_file(config_file): globals()[k] = v
would makes global lookbehinds unresolvable at compile time. So Python
solves the potential keyword/namespace-name ambiguity with a builltin
keyword definition list.
Similarly, avoiding global/local ambiguity is the reason why 'import *'
is now prohibited within function defs and why "locals[k] = v" has no
effect on the actual function local namespace. Python requires that the
status of names within functions be determined and determinable at
compile time.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list