Experiences/guidance on teaching Python as a first programming language

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Dec 19 01:21:06 CET 2013


On 18 December 2013 22:33, Terry Reedy <tjreedy at udel.edu> 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. 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. Given that a dict is returned, the rest is
> unambiguous.

It's not unambiguous. The full wording is:
'''
locals()

Update and return a dictionary representing the current local symbol
table. Free variables are returned by locals() when it is called in
function blocks, but not in class blocks.

Note:
The contents of this dictionary should not be modified; changes may
not affect the values of local and free variables used by the
interpreter.
'''

The part that says "changes may ..." is deliberately ambiguous; the
author didn't want to impose too strong a constraint on any particular
implementation.

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

That's not what is usually meant by "name-binding".

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

Agreed.

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

Incorrect. The code in question is:

    locals()['spam'] = 42

and it is semantically a no-op. The index assignment on a temporary
dict may actually be performed by e.g. the CPython interpreter but it
is really just dead code.


Oscar



More information about the Python-list mailing list