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>You're seeing name mangling in effect.  From the <a href="https://docs.python.org/2/tutorial/classes.html#tut-private" rel="nofollow">documentation</a>:</p>

<blockquote>
  <p>Any identifier of the form <code>__spam</code> (at least two leading underscores, at most one trailing underscore) is textually replaced with <code>_classname__spam</code>, where classname is the current class name with leading underscore(s) stripped. <strong>This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.</strong></p>
</blockquote>

<p>As far as I can think, the only way around this is to rename the <code>__outerVar</code> in the global scope to something that doesn't start with double underscores.</p>

python class python-3.x module scope