Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function parameter names that are the same as passed variables

Tags:

python

Is there anything wrong with the following?:

def foo(bar):
    for b in bar:
        print (b)

bar = ['hello', 'world']

foo(bar)

Often in my code I change the function parameters to a name that differs from the passed variable.

def foo(_bar):
    for b in _bar:
        print (b)

bar = ['hello', 'world']

foo(bar)

I do this just to be safe, but when other people look at the code, I think it would be great if I can keep the same name so they know exactly what is being passed.

like image 709
madeslurpy Avatar asked Jun 27 '17 13:06

madeslurpy


People also ask

What happens if parameter name is same as variable name?

Answer. When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.

Can parameters and arguments have the same name?

Show activity on this post. Yes, the names of the variables you pass in a function call can be the same as the names of the parameters in the function definition.

Can a function have a parameter with the same name as a global variable?

Yes it works like this as variables of same names are allowed provided that they are in different scopes.

Can we have same name for a function and variable?

You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!


1 Answers

From syntax perspective, there is nothing wrong with 1 example. Python follows LEGB rule when it tries to get variable value, so when you use bar as an argument, you rewrite global bar in scope of foo function.

like image 145
Vlad Sydorenko Avatar answered Oct 17 '22 03:10

Vlad Sydorenko