Skip to content
Advertisement

Use a different fixed type for interfaces defined in the base class for subclasses

I have a BaseList container that takes BaseItem‘s as items. I then derive a new list CustomList and I want it to hold CustomItem‘s.

How to I type methods in BaseList many methods to accept BaseItem. And also tell it to use CustomItem the derived list CustomList?

Here is the code I have so far:

JavaScript
JavaScript

Question

How can I define a type A and say in BaseList it should resolve to BaseItem and in CustomList it should resolve to CustomItem?

Tried so far

I tried using TypeVar with the bounds attribute, but I didn’t seem to get it work.

Constraints

I have more than just one subclass so I don’t want to re-implement all these methods with different types. Also there are many more of these methods with similar problems, like __contains__, __getitem__, class specific items, etc.

The type hints should be also resolved by PyCharm, as the goal is to get correct code-complete there.

Advertisement

Answer

Make BaseList class Generic:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement