I am using python 3.8 (same behavior in 3.9) and I have the below parent class (simplified to illustrate the example) where date is dynamically set when instantiating the class.
from datetime import datetime, timezone
import time
class Parent():
def __init__(self, date=datetime.now(timezone.utc).timestamp()):
self.date = date
def date_id(self):
return id(self.date)
instantiating a child class as below returns 10 times the same id for the variable self.date. My assumption was that on instantiating a new Child class it will create a new self.date variable.
class Child(Parent):
def __int__(self):
super().__init__()
for i in range(10):
time.sleep(1)
print(Child().date_id())
If I want to achieve the expected behavior I instead need to define my dynamic assignment in the __init__ body as such
class Parent():
def __init__(self):
self.date = datetime.now(timezone.utc).timestamp()
what is the mechanism in python that results in this behavior?
>Solution :
"The default values are evaluated at the point of function definition in the defining scope" (…) Important warning: The default value is evaluated only once.
Example from the docs:
i = 5
def f(arg=i):
print(arg)
i = 6
f()
will print 5