# HG changeset patch # Parent b6ee02acaae996b058391f2a5a87705d49d9d4f8 Issue #17546: Clarify locals() in function, class and global contexts diff -r b6ee02acaae9 Doc/library/functions.rst --- a/Doc/library/functions.rst Wed Nov 26 21:17:53 2014 -0800 +++ b/Doc/library/functions.rst Sat Dec 03 04:33:28 2016 +0000 @@ -762,13 +762,28 @@ .. function:: locals() - Update and return a dictionary representing the current local symbol table. - Free variables are returned by :func:`locals` when it is called in function - blocks, but not in class blocks. + Return a dictionary representing the current local symbol table. + The contents and update behaviour vary depending on where it is called: - .. 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. + * In a function body, comprehension, or generator expression, + the dictionary returned also includes non-local, non-global names. + The dictionary is an accurate snapshot of the local namespace at + the time of the call. If the namespace changes after the call, + the dictionary may become out of date, but it may also automatically + update at any time. The contents of the dictionary should not + be modified by the user; it is undefined whether such changes affect + the namespace or not. + + * In a class definition, or when using :func:`exec` or :func:`eval`, + the dictionary returned directly reflects the local namespace, + and does not include non-local names. Changes in the dictionary + immediately affect the namespace, and changes in the namespace + immediately affect the dictionary. For class namespaces, the + dictionary is the same object returned by :meth:`__prepare__`, + and is passed to the metaclass; see :ref:`prepare`. + + * At the module level, the dictionary returned is the global symbol table, + also returned by :func:`globals`. .. function:: map(function, iterable, ...)