Search code examples
pythonmultiple-inheritancepython-typing

Fix multiple inheritance with generic base classes


from typing import Generic, TypeVar, Any

R = TypeVar('R')
X = TypeVar('X')

class SizedIterator(Generic[X]):
    def __init__(self) -> None:
        pass

class TfmIterator(Generic[R],  SizedIterator):
    def __init__(self) -> None:
        pass

The above is a much simplified version of the code in https://github.com/autorope/donkeycar/blob/dev/donkeycar/pipeline/sequence.py.

Apparently that code worked fine in Python 3.6 and/or 3.7. However, it gives the following error when I try to run it in Python 3.9:

Traceback (most recent call last):
  File "/Users/Shared/Personal/mycar/simple1.py", line 10, in <module>
    class TfmIterator(Generic[R],  SizedIterator):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Generic, SizedIterator

My question is what can I do to keep the same type hints without running into the MRO error?


Solution

  • You can try this:

    from typing import Generic, TypeVar, Any
    
    R = TypeVar('R')
    X = TypeVar('X')
    
    
    class SizedIterator(Generic[X]):
        def __init__(self) -> None:
            pass
    
    
    class NewIterator(Generic[R]):
        def __init__(self) -> None:
            pass
    
    
    class TfmIterator(NewIterator, SizedIterator):
        def __init__(self) -> None:
            pass