Skip to content

Python code generation @staticmethod from_dict constructor not useable for inheritance #1583

@DavidBecht

Description

@DavidBecht

Hi,
we are using quicktype to generate python code from json schemas and then we use the generated classes as base classes for the real implementations. The generated classes consists of following constructors:

@staticmethod
def from_dict(obj: Any) -> 'PointBase':
  ...

In the Point class we use PointBase as base class:

class Point(PointBase)
  ...

And of course, if now Point.from_dict is used as constructor the resulting class is from type PointBase and not Point. This results in loosing all the additional implementations from Point class.

Solution:
I would suggest to use an @classmethod from_dict constructor with a generic mypy variable:

PointBaseGenericType = TypeVar('PointBaseGenericType ', bound='PointBase')

class PointBase:
    """Relative point."""
    x: float
    y: float

    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

    @classmethod
    def from_dict(cls: Type[PointBaseGenericType], obj: Any) -> 'PointBaseGenericType':
        assert isinstance(obj, dict)
        x = from_float(obj.get('x'))
        y = from_float(obj.get('y'))
        return cls(x, y)

This would solve all the issues and will make your generated code more useful and pythonic.

BR
David

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions