Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does Python lint want me to use different local variable name, than a global, for the same purpose

Tags:

python

pylint

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?

like image 402
Mark Galeck Avatar asked Aug 01 '14 02:08

Mark Galeck


People also ask

What is the difference between global and local in Python?

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:

What is a global variable in Python?

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.

What is a local variable in Python?

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.

What is the difference between global and local variables?

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.


1 Answers

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 imported, 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()
like image 144
Robᵩ Avatar answered Sep 27 '22 18:09

Robᵩ