[Python-ideas] global and nonlocal with atributes

Chris Angelico rosuav at gmail.com
Sun May 5 10:46:06 CEST 2013


On Sun, May 5, 2013 at 4:41 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> That way you can have both "global.x", "nonlocal.x" and "x" variables
>> without conflict.
>>
>> x = 10
>> def f(x):
>>     def g():
>>         # how can I set both "x" variables inside here?
>
>
> You can't, and you shouldn't need to. How hard is it for you to use a
> different name for the global and the local? There are billions of possible
> names to choose from, why use the same name for both?

The conflict already exists in another form, and with the same solution:

>>> def foo():
	list=[1,2,3]
	# ...
	return __builtins__.list()

>>> foo()
[]

We're allowed to shadow builtins, and what's more, there's a way to
explicitly call up the builtin even after it's been shadowed. If
nothing else, it allows a measure of simplicity with common names like
'id' - instead of having to pick a different name, you just go right
ahead and use the obvious one, knowing that the builtin _is_
retrievable. With globals, yes it's possible to reference them via
globals()["some_name"], but that looks ugly. Would the OP's proposal
look better if, instead of "globals.x", it were "__globals__.x"?  Or
possibly "__module__.x", that being a magic word that references your
current module, whatever-it-may-be?

ChrisA



More information about the Python-ideas mailing list