Home > Software design >  Python: Can a function and local variable have the same name?
Python: Can a function and local variable have the same name?

Time:12-16

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?

CodePudding user response:

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.

CodePudding user response:

The answer is yes. Functions are first class objects in Python. There is no fundamental difference between the "foo" function and "foo" variable. Both of those are references to the memory and both have a scope, so they are both equivalent to a variable. If you have define foo as function and then dont overwrite it locally, it will be like a global variable (taken from the upper level scope):

def foo():
  print(foo)

and then if you overwrite it with a local variable, it will just define a local variable within the function scope:

def foo():
  foo = 3
  print(foo)

In python every reference (variable) can be overwritten for the life span of a particular scope. You can try:

def foo(): pass
foo = 3

This will overwrite the value of the foo and it will point now to 3 instead to the function foo in the memory.

CodePudding user response:

Well, it is because of the scope of variable each foo is. The function foo() is in the global scope, therefore can be called within other functions and outside of functions.

The variable foo however, is in the local scope. That means it only "exists" inside of the function, it cannot be called or referenced outside of the function.

So, each different function creates its own local scope when it is called, and the variables created within are forgotten as soon as the scope is destroyed (the function ends).

Global variables can be accessed within local scope, local variables cannot be accessed in global scope.

If you want to create the variable in the global scope, call it like this:

global var

Here is an example of global and local scope:

var=1
def foo1():
  var=3
foo1()
print(var) #prints 1 because the "var" in foo1() is locally assigned
def foo2():
  global var
  var=2
foo2()
print(var) #prints 2 because "var" is global

So, your function works because it i only assigning the name foo locally, not globally.

However, if you call foo() later in that function, it will raise an error because that local scope has assigned an int value to foo, not a function, therefore is not callable.

CodePudding user response:

Eu ainda estou engatinhando, mais acredito que apesar de funcionar, o seu código não fica claro, podendo causar confusão.

Imagina num projeto grande em que tem muitas linhas de código você usar na variável o mesmo nome da função. Fica muito confuso, principalmente se não será você mesmo que vai refaturar o código no futuro.

  • Related