It seems to me that I should preface to this: Do not really do this.
You (sort) can with functions, but you also disable calls to all other global methods and variables, which I donβt think you would like to do.
You can use the following decorator to make the function act as if there are no variables in the global namespace:
import types noglobal = lambda f: types.FunctionType(f.__code__, {})
And then call your function:
a = 1 @noglobal def my_fun(x): print(x) print(a) my_fun(2)
However, this actually leads to a different error than you want, this leads to:
NameError: name 'print' not defined
By not allowing the use of global tables, you cannot use print() .
Now you can pass the functions that you want to use as parameters that will allow you to use them inside the function, but this is not a very good approach, and it is much better to just keep your global variables.
a = 1 @noglobal def my_fun(x, p): p(x) p(a) my_fun(2, print)
Output:
2 NameError: name 'a' is not defined
source share