Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

When running my lint, I am getting the error below:

Redefining name 'tmp_file' from outer scope (line 38) (redefined-outer-name)

Here is my snippet of code in that line:

tmp_file = open('../build/' + me_filename + '.js','w')
like image 250
r23712 Avatar asked Jul 28 '14 16:07

r23712


3 Answers

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.

like image 184
rodrigo Avatar answered Nov 08 '22 23:11

rodrigo


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.

like image 19
Packman Avatar answered Nov 08 '22 23:11

Packman


Open with with

Apart from @Rodrigo's correct answer about scopes: if your tmp_file is just that, a temporary file, you can use

with open('../build/' + me_filename + '.js','w') as tmp_file:
    # do something

in both cases. It clearly defines where your tmp_file is going to be used.

It is the recommended way of dealing with variables whose scope needs to be clearly bounded.

Error description

Pylint has a built-in description:

pylint --help-msg=redefined-outer-name

gives

:redefined-outer-name (W0621): Redefining name %r from outer scope (line %s) Used when a variable's name hide a name defined in the outer scope. This message belongs to the variables checker.

like image 7
serv-inc Avatar answered Nov 08 '22 23:11

serv-inc