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.
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.
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.
Yes it works like this as variables of same names are allowed provided that they are in different scopes.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With