Question Details

No question body available.

Tags

python python-3.x generics python-typing type-narrowing

Answers (2)

April 8, 2026 Score: 0 Rep: 165,928 Quality: Low Completeness: 50%

In your code, l3 looks like it is a list[BaseModel]. Why shouldn't this be allowed?

If you created a class NewerModel(NewModel): ... then you could store it in a list[NewModel]. Would that be allowed?

It almost sounds like you're trying to limit this to collections of objects that have identical types, ignoring type inheritance. This would violate the normal substitution rule, that DerivedClass is-a BaseClass and can be used anywhere BaseClass would be allowed. I don't think you can express that constraint in Python's typing rules.

April 8, 2026 Score: 0 Rep: 1 Quality: Low Completeness: 50%

So, I myself am exploring python after a while. And yes, it is possible to restrict your code to only have homogeneous sequences, but you can't guarantee it in python's type system as it is constructed to 'play it safe'.

You can use explicit type annotations unions instead of relying on just inference {l3: list[ExampleModel|NewModel]} , and try to enable stricter settings in your type checker (mypy/Pyright) so it can flag more reliably {strict=True} in your config.

Though, you can use a similar function to guarantee the homogeneity...

def func(b: Sequence[T]) -> T:
    firsttype = type(b[0]
    if not all(type(x) is firsttype for x in b):
        raise TypeError("Sequence must contain only one concrete type") 
    return b[0]

Hope it helps!!