title: In Python, is it possible to access the global namespace from within a function
body: <p>I'm learning Python coming from a good background with other languages. My question is mostly academic, as I know that what I'm asking is seldom needed and is definitely not a good programming practice.</p>
  
  <p>Here is what I'm asking:</p>
  
  <pre><code>x = 'global scope'      # global
  def func():
      x = 'local scope'   # global x is now shadowed
      print(global x)     # is this somehow possible?
  </code></pre>
  
  <p><strong>Attempt #1</strong></p>
  
  <pre><code>def attempt1():
      x = 'local scope'   # shadowded
      global x
      print(x)            # error
  </code></pre>
  
  <p>This results in an error: name 'x' is assigned to before global declaration.</p>
  
  <p><strong>Attempt #2</strong></p>
  
  <pre><code>def attempt2():
      x = 'local scope'   # shadowded
      print(__main__.x)   # error: __main__ not defined
  </code></pre>
  
  <p>The Python documentation on namespaces states suggest that #2 (or something like it) should be possible. See <a href="https://docs.python.org/3.5/tutorial/classes.html" rel="noreferrer">Python Tutorial 9.2</a></p>
  
  <blockquote>
    <p>"The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace."</p>
  </blockquote>
  
  <p>However attempting to access <code>__main__</code> from either a script or the console results in an error. Also, the global attribute <code>__name__</code> refers to the outermost module as <code>__builtins__</code>, but this only contains the built-in variables, not any user defined global ones.  If the variable were delcared in an outside module, one that had been imported, it could be accessed with <code>__module_name__.variable</code>.</p>