Python Tip #242 (of 365): Prefer isinstance over type for type checking. Do this...
Trey Hunner ๐ @treyhunner@mastodon.social
Python Tip #242 (of 365):
Prefer isinstance over type for type checking.
Do this:
isinstance(value, int)
Not this:
type(value) == int
Unlike comparing with type(...), using isinstance respects inheritance.
A "type(...) == ..." check fails for subclasses:
>>> counts = Counter("hello")
>>> isinstance(counts, dict)
True
>>> type(counts) == dict
False
Checking with type means nobody can inherit from your class without breaking your type check.
๐งต (1/2)