0

If I was trying to define a function that can take any object whose class type inherited from a specific base class, how can I define that using the typing module in python.

I have seen the example shown here: In python type-hinting, how can I make an argument accept any subclass of a base class?, but the answer accepted is specific. I would like a general one.

For example

import typing

class A:
   def __init__(self):
      pass

class B(A):
   def __init__(self):
      super(B, self).__init__()

class C:
   # typing.InstanceBase was used as an example method
   def __init__(self, object: typing.InstanceBase[A]):
      self.object = object

a = A()
b = B()
>> c1 = C(a)  # Would not complain about typing
>> c2 = C(b)  # Would not complain about typing
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Interlooper
  • 494
  • 2
  • 5
  • 14
  • 2
    The answer in the linked question mentions the general case. It says just use `object: A`. As B is a subclass of A, an instance of B can be expected to behave as an instance of A. – Dunes Feb 13 '19 at 20:41
  • The example given does exactly what you need. Remember that unless you enforce type with something like mypy, then only a type checker will warn about invalid types. – Alastair McCormack Feb 13 '19 at 21:39
  • Also, AFAIK, you can just do `def __init__(self, object: A):` – Alastair McCormack Feb 13 '19 at 21:42
  • Ahh I see okay, should I delete the question or should I point the solution to the one I linked to? – Interlooper Feb 14 '19 at 00:06

0 Answers0