10

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.

  • 3
    Yeah, there's no problem with that. [Here's a quick write up](https://stackoverflow.com/a/292502/7303349) of scoping in Python. – Simon Visser Jun 27 '17 at 13:51
  • 2
    using a different var name is unnecessary, the `bar` variable in the function scope would be a different one than that of the caller – dabadaba Jun 27 '17 at 13:51

4 Answers4

5

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.

Vlad Sydorenko
  • 601
  • 4
  • 6
3

You can keep the same name, it doesn't matter. Variables defined inside a function are not accessible outside.

BoilingFire
  • 191
  • 1
  • 9
2

Well, there's no problem because variables that are defined inside a function have local scope.

IMO, this problem only matters when your function need to use the same name local variable AND some global variable. But you should however avoid such design in the first place.

This is how I handle this kind of situations:

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

def main():
    bar = ['hello', 'world']
    foo(bar)
    ...

More, what should be worth mentioning is that in your second example, _variable is usually used for privatish (internal use) things in Python, but that's just a convention (It's not enforced by the language in any way, since Python programmers are all consenting adults). I'd rather use: variable_ instead.

1

The only risk with doing that is if you are using any global variable the scope of the variable has no impact.

Depending on the variable name, it COULD be confusing to use the same variable name, but I think you should really just use whatever makes the most sense given the context. So for example in something like

do_angle_computation(theta):
    return sin(theta) * cos(theta)

theta = 30
print do_angle_computation(theta)

it's totally fine.

fjafjan
  • 84
  • 1
  • 6