Why can't I define a class in main()?
<p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p>

<pre><code>class graph(object):
    def __init__(self):
        self.nodes = []
        self.edges = []
        self.graphDict = {}

    def addNodes(self):
        self.nodes.append(input("Enter the name for a new node: "))

def main():
    g = graph()

if __name__ == '__main__':
    main()
</code></pre>

<p>And in the console:</p>

<pre><code>&gt;&gt;&gt; g
Traceback (most recent call last):
  File "&lt;pyshell#29&gt;", line 1, in &lt;module&gt;
    g
NameError: name 'g' is not defined
</code></pre>

<p>Any ideas how to fix this?</p>

<p>A way you can do this is using <a href="https://ipython.org/install.html" rel="nofollow">IPython</a>. <a href="http://ipython.readthedocs.io/en/stable/api/generated/IPython.terminal.embed.html#IPython.terminal.embed.embed" rel="nofollow"><code>IPython.embed(<strong><em>**kwargs</em></strong>)</code></a> will start the terminal from whatever scope you are in.</p>

<pre><code>import IPython

def main():
    g = 'graph()'
    IPython.embed()

main()
</code></pre>



<pre><code>In [1]: g
Out [1]: 'graph()'
</code></pre>

<p>A slightly more hacky-way, which I could only recommend in development, is updating <a href="https://docs.python.org/3.5/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> with <a href="https://docs.python.org/3.5/library/functions.html#locals" rel="nofollow"><code>locals()</code></a>.</p>

<pre><code>def main():
    g = 'graph()'
    globals().update(locals())

main()
</code></pre>



<pre><code>&gt;&gt;&gt; g
'graph()'
</code></pre>

python class main