[Python-checkins] bpo-8264: Document hasattr and getattr behavior for private attributes (GH-23513)

ethanfurman webhook-mailer at python.org
Tue Feb 2 16:07:08 EST 2021


https://github.com/python/cpython/commit/2edaf6a4fb7e20324dde1423232f07211347f092
commit: 2edaf6a4fb7e20324dde1423232f07211347f092
branch: master
author: Ken Jin <28750310+Fidget-Spinner at users.noreply.github.com>
committer: ethanfurman <ethan at stoneleaf.us>
date: 2021-02-02T13:06:57-08:00
summary:

bpo-8264: Document hasattr and getattr behavior for private attributes (GH-23513)

Clarify ``getattr`` and ``setattr`` requirements for accessing name-mangled attributes

Co-Authored-By: Catalin Iacob <iacobcatalin at gmail.com>

files:
M Doc/library/functions.rst
M Doc/reference/expressions.rst

diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index f84353ce391d1..55dd3f03f929c 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -693,6 +693,13 @@ are always available.  They are listed here in alphabetical order.
    ``x.foobar``.  If the named attribute does not exist, *default* is returned if
    provided, otherwise :exc:`AttributeError` is raised.
 
+   .. note::
+
+      Since :ref:`private name mangling <private-name-mangling>` happens at
+      compilation time, one must manually mangle a private attribute's
+      (attributes with two leading underscores) name in order to retrieve it with
+      :func:`getattr`.
+
 
 .. function:: globals()
 
@@ -1512,6 +1519,13 @@ are always available.  They are listed here in alphabetical order.
    object allows it.  For example, ``setattr(x, 'foobar', 123)`` is equivalent to
    ``x.foobar = 123``.
 
+   .. note::
+
+      Since :ref:`private name mangling <private-name-mangling>` happens at
+      compilation time, one must manually mangle a private attribute's
+      (attributes with two leading underscores) name in order to set it with
+      :func:`setattr`.
+
 
 .. class:: slice(stop)
            slice(start, stop[, step])
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index 8ac626444843d..c8c9b4683e62d 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -77,6 +77,8 @@ When the name is bound to an object, evaluation of the atom yields that object.
 When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
 exception.
 
+.. _private-name-mangling:
+
 .. index::
    pair: name; mangling
    pair: private; names



More information about the Python-checkins mailing list