Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understand the behavior of `super.__init__()` with dynamic value in parent class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading