Experiences/guidance on teaching Python as a first programming language

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 19 18:06:05 CET 2013


On Wed, 18 Dec 2013 17:33:49 -0500, Terry Reedy wrote:

> On 12/18/2013 3:18 AM, Steven D'Aprano wrote:
> 
>> We don't know what locals()['spam'] = 42 will do inside a function,
> 
> I am mystified that you would write this.

Context is everything. locals() doesn't just return any old dictionary. 
It returns a dictionary of variables.


> Locals() will "Update and
> return a dictionary representing the current local symbol table." The
> only thing unspecified is the relation between the 'current local symbol
> table' and the *dict* that 'represents' it. 

Precisely.


> Given that a dict is returned, the rest is unambiguous.
> 
>> unlike the C case, we can reason about it:
>>
>> - it may bind 42 to the name "spam";
> 
> "somedict['spam'] = 42" will do exactly that.

We're not talking about setting items in an arbitrary dict. We're talking 
about setting variables using locals(), and in that case, writing to 
locals() does not guarantee to bind the value to the *name*.

def test():
    spam = 23
    locals()["spam"] = 42
    assert spam == 42


test() passes the assertion in IronPython 2.6, but fails in CPython 2.7 
and 3.4, and Jython 2.5.


>> - it may raise a runtime exception;
> 
> Absolutely not.

I don't know of any Python implementation which does so, but the 
documentation says:

     The contents of this dictionary should not be modified

so it is hardly beyond the realm of possibility that some implementation 
may choose to treat it as an error and raise an exception.


>> - it may even be a no-op;
> 
> Absolutely not.


In the example I show above, it is a no-op. The dict returned by locals 
is modified and then immediately garbage-collected. There are no side-
effects. Should some implementation decide to compile that away as dead 
code, it would be perfectly allowed to. (Well, assuming that it 
determined first that locals() actually was the built-in and not some 
substitute, either by static analysis or runtime testing.) It wouldn't 
surprise me if PyPy was capable of doing that today.



-- 
Steven



More information about the Python-list mailing list