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()
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With