[Python] Is it good practice to use typing.Union in an abstract method when child classes only...

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with abstract base classes in Python, and I'm wondering about best practices regarding method typing—particularly when using Union in the base class and narrower types in subclasses.

    In my case, I have an abstract method that accepts either a pd.DataFrame or a Dict[str, Any] as a parameter. But depending on the project, the subclasses will only accept one specific type:


    • Project A only accepts pd.DataFrame


    • Project B only accepts Dict[str, Any]

    So in my base class, I currently have:

    from abc import ABC, abstractmethod
    from typing import Union, Dict, Any
    import pandas as pd

    class ManifestExtract(ABC):

    @abstractmethod
    def extract_processed_samples_from_manifest(self, manifest: Union[Dict[str, Any], pd.DataFrame]) -> pd.DataFrame:
    pass


    And in the subclasses:

    class ManifestExtractProjectA(ManifestExtract):

    def extract_processed_samples_from_manifest(self, manifest: pd.DataFrame) -> pd.DataFrame:
    raise NotImplementedError

    class ManifestExtractProjectB(ManifestExtract):

    def extract_processed_samples_from_manifest(self, manifest: Dict[str, Any]) -> pd.DataFrame:
    raise NotImplementedError


    However, tools like Ruff complain:

    Method "extract_processed_samples_from_manifest" overrides class "ManifestExtract" in an incompatible manner
    Parameter 2 type mismatch: base parameter is type "Dict[str, Any] | DataFrame", override parameter is type "DataFrame"
    Type "Dict[str, Any] | DataFrame" is not assignable to type "DataFrame"


    Is using Union in the base class method the right approach when child classes only handle one type each? Or is it better to use Any in the base method to avoid typing conflicts? What's the Pythonic or best-practice way to design such a case?

    Continue reading...

Compartilhe esta Página