Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Python function scope to local variables only

Is there a way to limit function so that it would only have access to local variable and passed arguments?

For example, consider this code

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

Normally the output will be

2
1

However, I want to limit my_fun to local scope so that print(x) would work but throw an error on print(a). Is that possible?

like image 755
Tautvydas Avatar asked Mar 01 '18 17:03

Tautvydas


1 Answers

Nope. The scoping rules are part of a language's basic definition. To change this, you'd have to alter the compiler to exclude items higher on the context stack, but still within the user space. You obviously don't want to limit all symbols outside the function's context, as you've used one in your example: the external function print. :-)

like image 188
Prune Avatar answered Nov 11 '22 10:11

Prune