I am developing a Python application where i need many times to check if an object is a subclass of a DB model.
I did my own function to do that:
def isModel(obj):
return isinstance(obj, type) and issubclass(obj, Model)
issubclass raises exception of obj is not a class, but i would like it just return False if obj is not a class.
I thought better to make another function, to use instead of the built-in issubclass:
def _issubclass(obj, Klass):
return isinstance(obj, type) and issubclass(obj, Klass)
But why the built-in issubclass was not made like that? What’s the reason? Am i missing something?
UPDATE:
I have models:
class BaseModel(object):
id = Field(...)
class MyModel(BaseModel):
deleted = Field(...)
In a function i want check if an argument is a BaseModel:
def update_model(model):
assert isinstance(model, type) and issubclass(model, BaseModel), 'Must be a model'
issubclass answers the question if an object is a sub-class of the given class. If the object is a class instance, so the answer, IMO, should be ‘No, your object is not a BaseModel subclass, because it’s not a class at all’.
In Python is quite normal instead of if something is not None or len(something) != 0 to use if something and not raising any TypeError. What’s the usefulness of raising TypeError if the first argument of issubclass is not a class?
For example someone asks a dog: ‘Are you the right man to solve this task?’, and instead of answering ‘No’, the dog says ‘I am not a man’. I asked someone one thing (is sub class) and he didn’t answer my question.
Isinstance will probably do what you want.
isinstance(obj, Klass)will return True when obj is an instance of a class that is a subclass of Klass.Example:
“What’s the usefulness of raising TypeError if the first argument of issubclass is not a class?”
Explicit is better than implicit. You passed a non-class into issubclass. That indicates that you are doing something wrong. Therefore you get an error. If you seriously do want to pass instances to issubclass, you can catch that error:
Or, of course, you can do what you do: An extra check.
However, if it did not raise an error, then it would be impossible to catch the mistake of passing in an instance.
From what I understand, you want to make a check in an API or similar, that the object passed in is a subclass of BaseModel, and the user should not be allowed to pass in an instance. IMO, the correct thing to do there is to raise a TypeError if they pass in the wrong thing. Like so:
Making an assert there just means that you hide the fact that it is a type error to pass in the wrong thing.