I have a number of different objects that I can 'jsonify', these are custom object types:
class Jsonable(ABC):
@abstractmethod
def extract_json():
pass # return json of self
class Organization(Jsonable):
# implements the abstract method, all good here
def extract_json():
return # some json of self, great!
class Feature(Jsonable):
# implements the abstract method, all good here
def extract_json():
return # some json of self, great!
I have a function, where I want to pass in many different types of 'Jsonable' and get the json for them, but theres a catch, the 'str' class is a valid type to this function, and also a List[Jsonable] is also valid, how do I have a clean function for returning the data?
def extract(data: Union[Jsonable, List[Jsonable], str):
if isinstance(data, str):
# do something about string
# not great but I can live with this, it will never change
return data.extract_json() # ok for the standard types (Org above)
# what about List[Jsonable]?
# I have many types, Organization above is one example
How do I make this extract function not violate the OCP and get a nice clean way to abstract the data from these types? I should be able to get the json from the listed types aswell, cleanly?
The List can't really extend Jsonable, so how do I handle this cleanly?
Aucun commentaire:
Enregistrer un commentaire