Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the same name for variables which are in different functions?

I've been searching a while for my question but haven't found anything of use. My question is rather easy and straightforward.

Is it preferable or perhaps "pythonic" to use the same name for a certain variable which will appear in different functions, but with the same purpose?

For example:

def first_function():
    pt = win.getMouse() # This waits for a mouseclick in a graphical window.

    if blabla.button.clicked(pt):
        second_function()

def second_function():
    pt = win.getMouse() 

    if whatever.button.clicked(pt):
        third_function()

Does it matter if the variable reference (pt) to win.getMouse() in the second_function() has the same name as the variable in the first_function()? Or should the variable pt in the second function be named something else?

like image 593
Bondenn Avatar asked Dec 10 '13 11:12

Bondenn


3 Answers

Names in functions are local; reuse them as you see fit!

In other words, the names in one function have no relationship to names in another function. Use good, readable variable names and don't worry about names clashing.

like image 121
Martijn Pieters Avatar answered Nov 14 '22 22:11

Martijn Pieters


Its not about "Pythonic" or not. In programming you always wish your variables to have a meaning, if the same name occures in differend functions that means they do things with the same purpose or same params. Its fine to use same names in different functions, as long as they don't collide and make problems

like image 26
Lazybeem Avatar answered Nov 14 '22 21:11

Lazybeem


Variables defined in a function have Function Scope and are only visible in the body of the function.

See: http://en.wikipedia.org/wiki/Scope_(computer_science)#Python for an explanation of Python's scoping rules.

like image 31
James Mills Avatar answered Nov 14 '22 21:11

James Mills