Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function and local variable have the same name?

Tags:

python

scope

Here's an example of what I mean:

def foo():
    foo = 5
    print(foo + 5)

foo()
# => 10

The code doesn't produce any errors and runs perfectly. This contradicts the idea that variables and functions shouldn't have the same name unless you overwrite them. Why does it work? And when applied to real code, should I use different function/local variable names, or is this perfectly fine?

like image 330
jianmin-chen Avatar asked Dec 16 '21 10:12

jianmin-chen


1 Answers

foo = 5 creates a local variable inside your function. def foo creates a global variable. That's why they can both have the same name.

If you refer to foo inside your foo() function, you're referring to the local variable. If you refer to foo outside that function, you're referring to the global variable.

Since it evidently causes confusion for people trying to follow the code, you probably shouldn't do this.

like image 132
khelwood Avatar answered Sep 21 '22 18:09

khelwood