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

Question:

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')
Asked By: r23712

||

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.

Answered By: rodrigo

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.

Answered By: serv-inc

You get this error if you have defined the same variable in multiple places like outside the def and inside the def.

If you are using the single variable define it as global variable_name and use global keyword all the places. Else please rename the other variables.

Answered By: skipper21

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.

Answered By: Packman
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.