Given Python code such as
def func():
for i in range(10):
pass
for i in range(10):
pass
pylint complains
Redefining name 'i' from outer scope
What is the Pythonic way to write the above? Use a different variable locally, say j
?
But why, when the variable means exactly the same in both cases (i
for index). Let's say I change all local indexes to j
and then later I find I want to use j
as the second index in the glocal scope. Have to change again?
I can't disable lint warnings, I don't want to have them, I want to write Pythonic, and yet I want to use the same name for the same thing throughout, in the simple case like the above. Is this not possible?
Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example:
Below is the pictorial representation of a variable and it being stored in the memory. In Python or any other programming languages, the definition of global variables remains the same, which is “ A variable declared outside the function is called global function ”. We can access a global variable inside or outside the function.
Local variables are those which are initialized inside a function and belongs only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
Global variables can be used by everyone, both inside of functions and outside. If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function.
You can avoid global variable conflict by not having any global variables:
def func():
for i in range(10):
pass
def _init_func():
for i in range(10):
pass
_init_func()
Any code that needs to run at module-init time can be put into a single function. This leaves, as the only executable code to run during module init: def
statements, class
statements, and one function call.
Similarly, if your code is not intended to be import
ed, but rather is a script to be run,
def func():
for i in range(10):
pass
def main():
for i in range(10):
pass
if __name__=="__main__":
main()
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