Disable global variable lookup in Python
Question: In short, the question: **Is there a way to prevent Python from looking up
variables outside the current scope?**

Details:

Python looks for variable definitions in outer scopes if they are not defined
in the current scope. Thus, code like this is liable to break when not being
careful during refactoring:

    
    
    def line(x, a, b):
        return a + x * b
    
    a, b = 1, 1
    y1 = line(1, a, b)
    y2 = line(1, 2, 3)
    

If I renamed the function arguments, but forgot to rename them inside the
function body, the code would still run:

    
    
    def line(x, a0, b0):
        return a + x * b  # not an error
    
    a, b = 1, 1
    y1 = line(1, a, b)  # correct result by coincidence
    y2 = line(1, 2, 3)  # wrong result
    

I know [it is bad practice to shadow names
from](http://stackoverflow.com/a/20125739/3005167) outer scopes. However,
there are a few reasons why this is done anyway:

  * Sometimes it may make sense to have the same names because they refer to the same thing
  * One might run out of meaningful variable names
  * laziness

Is there a way to prevent Python from looking up variables outside the current
scope? (So that accessing `a` or `b` raises an Error in the second example.)

On account of being lazy, I would prefer a solution that works without
repeated boiler-plate code :)

If the issue is ambiguous in terms of Python version, I'm mostly interested in
Python 3.3 and above.


Answer: No, you cannot tell Python not to look names up in the global scope.

If you could, you would not be able to use _any_ other classes or functions
defined in the module, no objects imported from other modules, nor could you
use built-in names. Your function namespace becomes a desert devoid of almost
everything it needs, and the only way out would be to import everything into
the local namespace. _For every single function in your module_.

Rather than try to break global lookups, keep your global namespace clean.
Don't add globals that you don't need to share with other scopes in the
module. Use a `main()` function for example, to encapsulate what are really
just locals.

Also, add unittesting. Refactoring without (even just a few) tests is always
prone to create bugs otherwise.

