pythonfunctionscopeglobal-variables

How to disallow global variables in a function? (python)


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?


Solution

  • I feel like I should preface this with: Do not actually do this.

    You (sort of) can with functions, but you will also disable calls to all other global methods and variables, which I do not imagine you would like to do.

    You can use the following decorator to have the function act like 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 results in a different error than you want, it results in:

    NameError: name 'print' is not defined

    By not allowing globals to be used, you cannot use print() either.

    Now, you could pass in the functions that you want to use as parameters, which would allow you to use them inside the function, but this is not a good approach and it is much better to just keep your globals clean.

    a = 1
    @noglobal
    def my_fun(x, p):
        p(x)
        p(a)
    my_fun(2, print)
    

    Output:

    2
    NameError: name 'a' is not defined