Disable global variable lookup in Python

Yes, maybe not in general. However you can do it with functions.

The thing you want to do is to have the function’s global to be empty. You can’t replace the globals and you don’t want to modify it’s content (becaus
that would be just to get rid of global variables and functions).

However: you can create function objects in runtime. The constructor looks like types.FunctionType((code, globals[, name[, argdefs[, closure]]]). There you can replace the global namespace:

def line(x, a0, b0):
   return a + x * b  # will be an error

a, b = 1, 1
y1 = line(1, a, b)  # correct result by coincidence

line = types.FunctionType(line.__code__, {})
y1 = line(1, a, b)  # fails since global name is not defined

You can of course clean this up by defining your own decorator:

import types
noglobal = lambda f: types.FunctionType(f.__code__, {}, argdefs=f.__defaults__)

@noglobal
def f():
    return x

x = 5
f() # will fail

Strictly speaking you do not forbid it to access global variables, you just make the function believe there is no variables in global namespace. Actually you can also use this to emulate static variables since if it declares an variable to be global and assign to it it will end up in it’s own sandbox of global namespace.

If you want to be able to access part of the global namespace then you’ll need to populate the functions global sandbox with what you want it to see.

Leave a Comment