-2

I was surprised today to find out that the following appears to be valid code in Python:

def foo(n):
  foo = n * 10
  return foo

foo(5)

What in Python allows for a variable name to match the name of the function it is in? Is it just some kind of scoping rule that helps to keep these 2 things separate? so Python simply considers a program's function namespace to be a completely separate animal from the program's variable name space?

(Note: I would hate to do this in my own programs as it's a tad confusing but c'est la vie as they say in France.)

jwodder
  • 54,758
  • 12
  • 108
  • 124
Mad Max
  • 535
  • 4
  • 8

1 Answers1

2

There are two separate scopes at play here: the global namespace, and the local namespace of the function.

  • foo the function lives in the global namespace, because def foo(n): ... is executed at the top level of the module.
  • foo the integer is a local variable inside the foo() function. The name only exists while foo() executes. When return foo is executed, the function ends and all local variables are cleaned up.

So yes, here these two can live next to one another perfectly fine.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Though you couldn't then call the function `foo` after creating the local variable `foo`. – SirGuy Nov 01 '18 at 22:49
  • Outside of the function? You can call `foo()` just fine! Locals don’t affect globals. Inside the function the local name `foo` is set to something different, making it harder to access the function object, but not impossible. – Martijn Pieters Nov 02 '18 at 00:05