0

I have an API that receives a serialized representation of an object that I expect to comply with a particular interface (known at development time). The serialized data I receive includes details that are used to create implementations of the methods/properties of this interface, so the actual object gets constructed at runtime; however, method names, signatures, property types, etc. are expected to match those known from the interface at development time. I would like to be able to construct this object at runtime, and then verify interface compliance, preferably failing immediately once an invalid object is constructed, not just when I try to invoke a method that's not there.

I am new to Python, so I am not sure if there is an idiomatic way of doing such a check. I have investigated using Abstract Base Classes, and annotating my constructed object with such a class. Using annotations is convenient during development time because I can get intellisense in VSCode, but they are not used to verify that my constructed object implements the ABC correctly at runtime - for example, when it is passed into a method as a parameter, like this:

def my_method(self, generated_object: MyABC):

Is there another approach to doing what I have described (casting/coercing to the ABC, or perhaps using a different language feature)? Or is my best bet to implement my own validator that will compare the methods/properties on the constructed object vs those on the ABC?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
SlyCaptainFlint
  • 501
  • 1
  • 4
  • 12

1 Answers1

0
import abc

class Base(abc.ABC):
    @abc.abstractmethod
    def i_require_this(self):
        pass

class Concrete(Base):
    def __init__(self):
        return

concrete = Concrete()

TypeError: Can't instantiate abstract class Concrete with abstract methods i_require_this

GlenRSmith
  • 786
  • 7
  • 12