Limit Python scope to local variables only

Is there a way to restrict a function so that it has access only to a local variable and passes arguments?

For example, consider this code

a = 1 def my_fun(x): print(x) print(a) my_fun(2) 

Usually the output will be

 2 1 

However, I want to limit my_fun local area so that print(x) works, but gives an error on print(a) . Is it possible?

+5
source share
2 answers

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 
+1
source

Nope. Scope rules are part of the basic language definition. To change this, you will have to change the compiler to drop the elements above into the context stack, but still within the user space. Obviously, you do not want to limit all characters outside the context of the function, since you used it in your example: the external function print . print

+3
source

Source: https://habr.com/ru/post/1275650/


All Articles