Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Can a function and local variable have the same name?

Here’s a 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading