I am getting the error 'redefined-outer-name'

That happens because you have a local name identical to a global name. The local name takes precedence, of course, but it hides the global name, makes it inaccesible, and cause confusion to the reader.

Solution

Change the local name. Or maybe the global name, whatever makes more sense. But note that the global name may be part of the public module interface. The local name should be local and thus safe to change.

Unless... your intention is for these names to be the same. Then you will need to declare the name as global in the local scope:

tmp_file = None

def do_something():
    global tmp_file # <---- here!
    tmp_file = open(...)

Without the global declaration, the local tmp_file will be unrelated to the global one. Hence the warning.


Solution

Create main() function which be holding all the main logic etc.

def pow(x):
    return x ** 2

def add(x, y):
    return x + y

def main():
    x, y = 2, 4
    print(pow(x))
    print(add(x, y))

if __name__ == '__main__':
    main()

Explanation

This works, because every new function instance creates a new local scope.

Tags:

Python