On 2/26/2018 1:55 PM, Kirill Balunov wrote:
Hi,
I am a little bit confused with `locals` builtin in these moments:
1. The documentation says that _free varaibles_ are returned, which seems
incorrect description. In my mind the term free variable refers to
variables used in a function that are not local variables nor parameters of
that function.
I disagree with the terminology used in this section of the docs, so I
won't defend or explain.
The important points are that 1. *Python* code is that executed in the
context of multiple directly accessible namespaces; 2. there is more
than one way to implement a namespace; 3. the Python namespace system
has grown in complexity since the beginning; and 4. some details depend
on the implementation (CPython versus others) and Python and therefore
implementation version.
The point of point 3 is that terminology and details would likely be
different if Python were freshly designed more or less as it is today,
and some things only make more or less sense in historical context.
Learn what you need to know to write code that works.
The program namespace is called 'builtins'. Treat it as readonly. The
namespace, as opposed to its contents, cannot be accessed unless imported.
Each module namespace is accessed as globals(). It must be a dict. The
names of builtins are accessed as it they were in globals, even though,
in CPython, they are not. (I believe 'globals' predates multi-module
programs.)
The local namespace is the default recipient of name bindings from
assignment, class, and def statements.
At module scope, the local namespace is the module or global namespace.
A binding in module locals == globals can mask a builtin. 'def print():
pass'. Deletion of that binding unmasks the builtin. 'del print'. (If
an implementation actually initialized each globals() by copying
builtins, then each deletion would have to check for possible unmasking.)
Class statements get a new local namespace, which defaults to some sort
of mapping. When the class statement finishes, the local names become
class attributes.
Be default, function local namespaces in CPython are implemented as
arrays, with local names compiles as indexes in the array.
Calling surrounding function local names collectively 'nonlocals' is the
result of months of bikeshedding.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list