When specifying a default argument in a Python function as a new object, calling the method several times doesn't actually create a new object. It just returns the same object. Could someone explain why there is a difference between code 1 and 2?
I was expecting that in all cases a brand new object is created.
Code 1
class MyObj:
pass
def make_my_obj(arg=MyObj()):
return arg
# o1 and o2 are the same object
o1 = make_my_obj()
o1
<__main__.MyObj object at 0x043EDEC8>
o2 = make_my_obj()
o2
<__main__.MyObj object at 0x043EDEC8>
Code 2
def make_my_obj_2(arg=None):
if arg is None:
arg = MyObj()
return arg
# o3 and o4 are different objects
o3 = make_my_obj_2()
o4 = make_my_obj_2()
o3
<__main__.MyObj object at 0x001B2E08>
o4
<__main__.MyObj object at 0x001AB9D0>