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.

classification
Title: Name mangling overrides externally defined names
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.5
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: ethan.furman, madphysicist
Priority: normal Keywords:

Created on 2016-01-07 19:28 by madphysicist, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg257714 - (view) Author: Joseph Fox-Rabinovitz (madphysicist) * Date: 2016-01-07 19:28
I will begin by including three code snippets that do not work to illustrate the issue. All snippets were run as python modules/scripts from the command line using "python snippet.py":

**1**

__a = 3
print(locals())
class T:
    def __init__(self):
        global __a
        self.a = __a
t1 = T()

**2**

__a = 3
print(locals())
class T:
    def __init__(self):
        self.a = __a
t2 = T()

**3**

__a = 3
print(locals())
class T:
    def __init__(self):
        m = sys.modules[__name__]
        self.a = m.__a
t3 = T()

All three snippets fail in the line assigning `self.a`. The first two produce `NameError: name '_T__a' is not defined`. The third produces `AttributeError: module '__main__' has no attribute '_T__a'`. The problem in all three cases is that name mangling supercedes any other operation to the point that it mangles elements that are explicitly stated not to belong to the class. This behavior is not intuitive or expected.

I am running `Python 3.5.1 :: Continuum Analytics, Inc.` (using the Anaconda platform) on a Red Hat 6.5 machine. I have tried the same thing on Arch Linux (also with Python 3.5.1 and anaconda) with identical results.
msg257715 - (view) Author: Ethan Furman (ethan.furman) * (Python committer) Date: 2016-01-07 19:56
Nice work with the debugging. but what you have proved is that Python is behaving exactly as designed [0].

While true that the current implementation does have the pitfall you have discovered, removing it is not worth the cost in complexity.

The proper "fix" is not to have __vars outside of a class.


[0] [https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references]
History
Date User Action Args
2022-04-11 14:58:25adminsetgithub: 70232
2016-01-07 19:56:17ethan.furmansetstatus: open -> closed
resolution: not a bug -> rejected
messages: + msg257715
2016-01-07 19:53:06ethan.furmansetnosy: + ethan.furman

resolution: not a bug
stage: resolved
2016-01-07 19:28:19madphysicistcreate