Double sided double underscored variable names

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Sep 11 21:14:16 EDT 2012


And again, Joshua's original post is not available from my provider. 
Joshua, I suspect that something about your post is being seen as spam 
and dropped by at least some providers.


On Wed, 12 Sep 2012 08:52:10 +1000, Chris Angelico wrote:

> On Wed, Sep 12, 2012 at 8:48 AM, Joshua Landau
> <joshua.landau.ws at gmail.com> wrote:
>>
>> Well, the problem is that a lot of collisions aren't predictable.
>> "locals()['foo'] = 2", for example. If it weren't for Python's annoying
>> flexibility* 

I can't see your footnote there, so you may have already covered this, 
but for the record, what you call Python's "annoying flexibility" is 
fundamental to Python's programming model and done so for good reasons. 
The ability to shadow built-ins is, at times, incredibly useful rather 
than annoying.

The world is full of bondage and domination languages that strongly 
restrict what you can do. Python doesn't need to be another one of them. 
Python's optimizing compiler, PyPy, is able to optimize code very well 
without such restrictions.


>> I would definitely do something very close to what you
>> suggest. Remember that "locals()" isn't Python's only introspection
>> tool. How about "from foo import *"?

I wouldn't call "import *" an introspection tool. At least, no more so 
than print.


> You're not supposed to mutate locals(), 

It's not so much you're not allowed to do it, but that the result of 
making changes to locals() inside a function is implementation dependent:

CPython 2: writing to the dict returned by locals() will work, but the 
changes will not be reflected in the actual local variables, except under 
very restricted circumstances;

CPython 3: those restricted circumstances that allowed writes to locals() 
to modify local variables are now SyntaxErrors;

Stackless: presumably the exact same behaviour as CPython (since 
Stackless is a fork, not a re-implementation);

Jython: the same as CPython;

IronPython: writes to locals() will modify the corresponding local 
variable.


Outside of a function, locals() returns globals() and writes will always 
modify the global variable (this is a language guarantee).

> but I suppose globals() works the same way.
> 
> Inline functions? I like this idea. I tend to want them in pretty much
> any language I write in.

What do you mean by in-line functions? If you mean what you literally 
say, I would answer that Python has that with lambda.

But I guess you probably mean something more like macros.


-- 
Steven



More information about the Python-list mailing list