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

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?

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.

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

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.

Related

"Global variable" in multiple functions

I am trying to collect data with a global variable, without returning the variable
def collect_result(result):
is_global = "Res_collected" in globals()
if is_global == False:
global Res_collected
Res_collected = []
elif is_global == True:
Res_collected.append(result)
return
How can I use or call this variable in another function?
You don't need to do anything special in order to read the value of a global variable inside another function, you can just refer to it by name, so print(Res_collected), for example.
If you want to write to the global variable, you would do that in the same way you're already doing it in your collect_result function, by using the global keyword. This is a decent introductory tutorial.
As others have already pointed out, it's generally not a good idea to use global variables. A better alternative is to pass your collection of results as a parameter to whatever functions are going to use them. That way it is clear and explicit what data is being read or modified by each function.
Global variables can hide important clues about what data is being used, where and how, which makes the code harder to understand, and can lead to other problems further down the line.
This is a really bad idea to use globals as indicated by #quamrana and #deceze but if you want to try (not for production please), I suppose the code below should work:
>>> globals().setdefault('Res_collected', []).append(res)

How can I pass on called function value in Python?

Let's say I have a code like this:
def read_from_file(filename):
list = []
for i in filename:
value = i[0]
list.append(value)
return list
def other_function(other_filename):
"""
That's where my question comes in. How can I get the list
from the other function if I do not know the value "filename" will get?
I would like to use the "list" in this function
"""
read_from_file("apples.txt")
other_function("pears.txt")
I'm aware that this code might not work or might not be perfect. But the only thing I need is the answer to my question in the code.
You have two general options. You can make your list a global variable that all functions can access (usually this is not the right way), or you can pass it to other_function (the right way). So
def other_function(other_filename, anylist):
pass # your code here
somelist = read_from_file("apples.txt")
other_function("pears.txt.", somelist)
You need to "catch" the value return from the first function, and then pass that to the second function.
file_name = read_from_file('apples.txt')
other_function(file_name)
You need to store the returned value in a variable before you can pass it onto another function.
a = read_from_file("apples.txt")
There are at least three reasonable ways to achieve this and two which a beginner will probably never need:
Store the returned value of read_from_file and give it as a parameter to other_function (so adjust the signature to other_function(other_filename, whatever_list))
Make whatever_list a global variable.
Use an object and store whatever_list as a property of that object
(Use nested functions)
(Search for the value via garbage collector gc ;-)
)
Nested functions
def foo():
bla = "OK..."
def bar():
print(bla)
bar()
foo()
Global variables
What are the rules for local and global variables in Python? (official docs)
Global and Local Variables
Very short example
Misc
You should not use list as a variable name as you're overriding a built-in function.
You should use a descriptive name for your variables. What is the content of the list?
Using global variables can sometimes be avoided in a good way by creating objects. While I'm not always a fan of OOP, it sometimes is just what you need. Just have a look of one of the plenty tutorials (e.g. here), get familiar with it, figure out if it fits for your task. (And don't use it all the time just because you can. Python is not Java.)

Can I use same argument names when passing arguments in Python

Can you please help me guys. I believe I've got pretty easy questions but don't want to stuff up with my assignment. I'm going to have Class in my module, this class will have few functions.
I just want to be sure it works alright and this is a not ugly code practice.
I.e. my first function test_info accepts one parameter test_code and returns something and the second function check_class accepts two parameter, one of them is called test_code as well
Can I use same argument name: test_code? Is it normal code practice?
def test_info (self, test_code):
my_test_code = test_code
#here we'll be using my_test_code to get info from txt file and return other info
def check_class (self, test_code, other_arg):
my_test_code = test_code
#here some code goes
Also is it fine to use my_test_code in both functions to get argument value or is it better to use different ones like my_test_code_g etc.
Many thanks
Yes you may.
The two variables test_code are defined only in the scope of their respective functions and therefore will not interfere with one another since the other functions lie outside their scope.
Same goes for my_test_code
Read online about variable scopes. Here is a good start
There is no technical reason to resolve this one way or another. But if the variables don't serve exactly the same purpose in both functions, it's confusing for a human reader if they have the same name.

Functions access to global variables

I am working on a text-based game to get more practice in Python. I turned my 'setup' part of the game into a function so I could minimize that function and to get rid of clutter, and so I could call it if I ever wanted to change some of the setup variables.
But when I put it all into a function, I realized that the function can't change global variables unless you do all of this extra stuff to let python know you are dealing with the global variable, and not some individual function variable.
The thing is, a function is the only way I know of to re-use your code, and that is all I really need, I do not need to use any parameters or anything special. So is there anything similar to functions that will allow me to re-use code, and will not make me almost double the length of my code to let it know it's a global variable?
You can list several variables using the same global statement.
An example:
x = 34
y = 32
def f():
global x,y
x = 1
y = 2
This way your list of global variables used within your function will can be contained in few lines.
Nevertheless, as #BrenBarn has stated in the comments above, if your function does little more than initializating variables, there is no need to use a function.
Take a look at this.
Using a global variable inside a function is just as easy as adding global to the variable you want to use.

add a local variables to a function

is it possible to add a local varible to a function, just before calling it ? if yes how ?
EDIT:REASON
i noticed that all my views in django are using
render_to_response(template_name,locals())
now i created a middleware and i wanted to add one more local variable using the
def process_view():
method of it .so that i don't have to modify the views .
The local scope for a function does not exist until the function is called, so it's not possible to do this. You could do this for a closure, but the next person to have to maintain the code would hunt you down and kill you.
Although I also think it is pretty useless, I thought that you may enclose the function in either a 'with' statement or another function, like the code below. Of course, this approach can be accomplished directly within the function of interest. In fact, you are adding the local variable 'during' the function declaration. See if this fits your needs!
#!/usr/bin/python
def my_funct(_local):
"""My function of interest
"""
print "Local argument was %s" % str(_local)
return "Finished"
def localize(fct, local_var):
"""
"""
return fct(_local = local_var)
## Use function to 'localize' variable
localize(my_funct, local_var="LOCAL_VARIABLE")
## Same effect without supplementary function :
my_funct(_local="LOCAL_VARIABLE")
try:
print local_var
except:
print "No such global variable"
Just some thoughts :)
Cheers
So if you’re one of those lazy
programmers and you like keeping code
particularly concise, you can take
advantage of a built-in Python
function called locals(). It returns a
dictionary mapping all local variable
names to their values, where “local”
means all variables that have been
defined within the current scope.
source
It is a trick in order to not have to explicitly list all of the variables you need to pass in to the function. In this case, you need to explicitly state a variable to pass in. Therefore, you should not be using locals() in the calls you are making in your middle-ware, as the trick was not designed to be used like that.
i mangaged to do that using decorators.

Categories