7

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?

1
  • Only in the example provided (2 functions, equal scope) is this totally OK. Conversely: totally NOT OK if there's any overlapping scope (global, main vs function, or nested functions) and pylint will flag it with a warning. Commented Aug 23, 2022 at 3:52

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

For example, there's no need to come up with a dozen variations on i or item for a dozen for loops in a dozen functions.
@MartijnPieters Okey thank you this answers my questions. I find the readability better if I'm using the same variable namefor all the variables refering to win.getMouse() in my program.
Exactly; and the Zen of Python states that readability counts. Readability is Pythonic.
2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.