Home > Net >  can we update mutable datatypes(like list) inside function without global keyword in python?
can we update mutable datatypes(like list) inside function without global keyword in python?

Time:02-02

If yes so can we conclude that in python we can update mutable datatypes anywhere inside program without global keyword and we cannot update immutable datatypes without global keyword?

CodePudding user response:

You can't ever modify an immutable object, with or without the global keyword. You can use global to reassign a variable that's in an outer scope, but that's not the same thing as modifying the object that the variable points to.

foo = 5
bar = foo

def update_foo():
    global foo
    foo  = 3

print(foo, bar)  # 5 5
update_foo()
print(foo, bar)  # 8 5

In the above example, we use global to reassign the foo variable in the outer scope, but the actual object that foo points to remains unchanged, which is why bar retains the value 5.

Compare this to what happens when we mutate a mutable object, like a list:

foo = [5]
bar = foo

def update_foo():
    # "global foo" has no effect one way or the other here
    foo[0]  = 3

print(foo, bar)  # [5] [5]
update_foo()
print(foo, bar)  # [8] [8]

Note that global foo wouldn't do anything here because we're not reassigning the variable foo, we're instead modifying the object that it points to (and this is something that's only possible with mutable objects -- you'll get an error if you try to do foo[0] = 3 on a tuple, because tuples are immutable).

If we reassign the variable foo:

foo = [5]
bar = foo

def update_foo():
    global foo
    foo = [foo[0]   3]

print(foo, bar)  # [5] [5]
update_foo()
print(foo, bar)  # [8] [5]

then the behavior with the list is the same as it is with the int, because we haven't actually modified the underlying object, just reassigned one of the variables to point to an entirely new object.

Obligatory link: https://nedbatchelder.com/text/names.html

CodePudding user response:

global keyword pertains to the scope of a variable, not mutability. global is used to make a locally assigned variable available globally.

  •  Tags:  
  • Related