Referring to outer scope from python class
<p>I have a (simplified) module, something like this:</p>

<pre><code>import tkinter as tk

__outerVar = {&lt;dict stuff&gt;}

class Editor(tk.Frame):
...
    def _insideFunction(self):
        for p in __outerVar.keys():
            &lt;do stuff&gt;
</code></pre>

<p>I'm getting a <code>NameError: name '_Editor__outerVar' is not defined</code> on the use of <code>__outerVar</code> when I try to instantiate Editor.  I tried putting "<code>global __outerVar</code>" at the top of <code>insideFunction</code>, even though I'm not writing to <code>__outerVar</code>, same error.</p>

<p>I'm sure I'm just misunderstanding some python scope rule here.  Help?</p>

<p>py 3.5</p>

<p>Python replaces any names preceded by a double underscore <code>__</code> in order to simulate 'private attributes'. In essence <code>__name</code> becomes <code>_classname__name</code>. This, called name mangling, happens only within classes as documented <a href="https://docs.python.org/3/tutorial/classes.html#private-variables" rel="nofollow">in the docs</a>:</p>

<blockquote>
  <p>This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.</p>
</blockquote>

<p>The solution is don't use <code>__name</code> names, using something like <code>_name</code> or just <code>name</code> suffices.</p>

<p>As an addendum, in <a href="https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables" rel="nofollow"><code>PEP 8 -- Method Names and Instance Variables</code></a> it states:</p>

<blockquote>
  <p>Python mangles these names with the class name: if class <code>Foo</code> has an attribute named <code>__a</code> , it cannot be accessed by <code>Foo.__a</code> . (An insistent user could still gain access by calling <code>Foo._Foo__a</code>.) <em>Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.</em></p>
</blockquote>

<p>So, unless you're designing for cases were subclass name clashing might be issue, don't use double leading underscores.</p>

python class python-3.x module scope