Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadows name xyz from outer scope

I am using pycharm and it lists out all the errors/warnings associated with the code. While I understand most of them I am not sure of this one "Shadows name xyz from outer scope". There are a few SO posts regarding this: How bad is shadowing names defined in outer scopes? but then they seem to be accessing a global variable.

In my case, my __main__ function has a few variable names and then it is calling another function sample_func which uses those variable names again (primarily the loop variable names). I am assuming because I am in a different function, the scope for these variables will be local, however the warning seem to suggest otherwise.

Any thoughts? For your reference here is some code:

def sample_func():     for x in range(1, 5):  --> shadows name x from outer scope         print x  if __name__ == "__main__":     for x in range(1, 5):         sample_func() 
like image 808
The Wanderer Avatar asked Jul 22 '15 23:07

The Wanderer


People also ask

How do you prevent shadows from outer scope?

I know it is bad practice to access variable from the outer scope, but what is the problem with shadowing the outer scope? To turn off this message in PyCharm: <Ctrl>+<Alt>+s (settings), Editor, Inspections, "Shadowing names from outer scopes". Uncheck.

What does shadows name mean in Python?

As Wikipedia says, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.


1 Answers

The warning is about the potential danger you are introducing by re-using these names at inner scopes. It can cause you to miss a bug. For example, consider this

def sample_func(*args):     smaple = sum(args) # note the misspelling of `sample here`     print(sample * sample)  if __name__ == "__main__":     for sample in range(1, 5):         sample_func() 

Because you used the same name, your misspelling inside the function does not cause an error.

When your code is very simple, you will get away with this type of thing with no consequences. But it's good to use these "best practices" in order to avoid mistakes on more complex code.

like image 168
mehtunguh Avatar answered Oct 24 '22 20:10

mehtunguh