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

What is the best way for a class definition with PEP 526

Lets say I have a class like below:

Class Foo:
    x: int
    y: List[int]
    z: int = 5

    def __init__(self, x:int, z: int = 5):
        self.x = x
        self.y = []
        self.z = z

   ### some other methods

My questions are;

  1. If I am using the types inside the init function, isn’t me using types at the class level become redundant?

    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

  2. I want the variable y to be initialized to an empty list for each instance. So, I didn’t write the below code as it initialized the y at the class level. Is my understanding correct?

    Class Foo:
       x: int
       y: List[int] = []
       z: int = 5
    
       def __init__(self, x:int, z: int = 5):
           self.x = x
           self.z = z
    

I’m trying to improve my code quality, so if I am missing some primary understanding regarding it, please let me know.

Thank you in advance.

>Solution :

Class-level type hints are still helpful — they’re good for documentation and static analysis, even if you also use them elsewhere.

Initializing mutable types like y inside init helps avoid shared state between instances, avoiding bugs that can be hard to track down.

Your current implementation is good practice re: 526

Sources:

My articles: https://ioflood.com/blog/python-type-hints/ and https://ioflood.com/blog/mutable-vs-immutable-in-python-object-data-types-explained/#Dangers_of_using_mutable_default_arguments

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