This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: access python private variable
Type: behavior Stage: resolved
Components: Build Versions: Python 3.8
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: AluminumPirate, steven.daprano
Priority: normal Keywords:

Created on 2021-03-16 17:20 by AluminumPirate, last changed 2022-04-11 14:59 by admin. This issue is now closed.

File name Uploaded Description Edit AluminumPirate, 2021-03-16 17:20 access python private variable
Messages (2)
msg388862 - (view) Author: David Elmakias (AluminumPirate) * Date: 2021-03-16 17:20
It might be my lack of knowledge in python, however I find this behavior a bit strange.

By declaring a private variable in a class, python creates an attribute with the name '_<ClassName>__<PrivateVariableName>'.
Both are located on a different location in memory.

I found that by assigning data to the created variable with the exact name/notation '_<ClassName>__<PrivateVariableName>' I changed the private variable data.
msg388864 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-03-16 17:45
This is not a bug, it is working as intended.

Python does not really support "private" attributes, except by convention. Names that begin with a single leading underscore are no different than any other name to the interpreter, but the reader is expected to not touch it.

Double-underscore names are no different, except that they have their names mangled so that subclasses can have their own version of the attribute that doesn't clash with that of the parent class.

Most people find that the double-underscore attributes are not worth the trouble. However you may like to read this:

By the way, attributes and variables in Python don't have fixed memory addresses. Whatever you did to make you think that:

"Both are located on a different location in memory."

you have misinterpreted what you are seeing.

There is no language feature to get the memory address of any object or variable in Python, except perhaps as an accident of implementation. And some interpreters include compacting garbage collectors that can move objects around memory.
Date User Action Args
2022-04-11 14:59:42adminsetgithub: 87685
2021-03-16 17:45:04steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg388864

resolution: not a bug
stage: resolved
2021-03-16 17:20:30AluminumPiratecreate