Is it appropriate to subclass the parent's parameters in subclass __init__'s within python?

55 views Asked by At

See the code example below.

My IDE highlights "do_something_special" as Unresolved attribute reference 'do_something_special' for class 'ParentAttribute'

This makes me suspect that this is an anti-pattern and I should be doing something different to accomplish the same goal (creating more complex instances of a specific pattern without repeating code).

What is the best practice for accomplishing this?

Here is a simple example. I expected this to be treated as valid Python by my IDE.

class ParentAttribute:

    def __init__(self):
        ...

class Parent:

    def __init__(self,
                 x: ParentAttribute
                 ):
        self.x = x


class ChildAttribute(ParentAttribute):

    def __init__(self):
        super().__init__()
        ...

    def do_something_special(self):
        ...

class Child(Parent):

    def __init__(self,
                 x: ChildAttribute
                 ):
        super().__init__(x=x)
        self.x.do_something_special()
1

There are 1 answers

2
johncs On

You can add a type for x in Child.

class Child(Parent):

    x: ChildAttribute

    def __init__(self,
                 x: ChildAttribute
                 ):
        super().__init__(x=x)
        self.x.do_something_special()

This could be unsafe if anything ever assigns x to a ParentAttribute though. For example:

child = Child(ChildAttribute())
parent: Parent = child
parent.x = ParentAttribute()

# Runtime error, not caught by type checker
child.x.do_something_special()

This may be an acceptable level of type safety for you, but depending on your needs you may want to guard against changes to x using a setter and getter, or even type x as ChildAttribute | ParentAttribute and use type guards every time you access a property of x unique to ChildAttribute.