Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show that function is mutable in Python?

My understanding of mutability and immutability in Python is, say we have a variable foo, if there exists a way to change how foo looks like (by using print) without changing its id, then foo is mutable. Otherwise, it's immutable.


For example, you can do this for a list,

foo = [1, 2, 3]
print(foo, id(foo))
foo[0] = 100
print(foo, id(foo))

but no way for int.


But what about function? First of all, is my definitions of mutability and immutability given above correct? If yes, can you find a way to mutate function without changing its id in order to prove it's mutable?

like image 512
Nicholas Avatar asked Sep 02 '25 16:09

Nicholas


1 Answers

You can explicitly change the code of a function without affecting its id (here is code using python 2.7):

>>> def f():
...     print "f"
...
>>> def g():
...     print "g"
...
>>> id(f)
140305904690672
>>> f()
f
>>> f.func_code = g.func_code
>>> id(f)
140305904690672
>>> f()
g
like image 173
Thomas Nyberg Avatar answered Sep 04 '25 06:09

Thomas Nyberg