1

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>
Payam Mesgari
  • 953
  • 1
  • 19
  • 38
  • Because default arguments are only evaluated once - when the function itself is created. Your second example is the proper way to use a default argument that "refreshes" with each call. – jfaccioni Sep 01 '20 at 20:43

0 Answers0