This product is not supported for your selected Datadog site. ().

Metadata

ID: python-best-practices/type-check-isinstance

Language: Python

Severity: Notice

Category: Best Practices

Description

This rule encourages the use of isinstance() instead of direct comparisons with type() when checking an object’s type. Using isinstance() is more flexible and idiomatic in Python, allowing checks for subclass relationships rather than requiring an exact type match. Relying on type() can lead to brittle code that fails to recognize instances of subclasses, which can reduce code reuse and make your program less adaptable to future changes. In contrast, isinstance() supports polymorphism by validating whether an object is an instance of a class or any of its subclasses.

If you want to check the type and subtypes, replace expressions like type(obj) == SomeClass with isinstance(obj, SomeClass). This rule should be ignored if you want to only check the current type of the value.

Non-Compliant Code Examples

# use isinstance instead of
if type(Foo()) == Foo:
    print("is foo")

Compliant Code Examples

raise ValueError("target %s config %s has type of %s" % (target, config_content, type(config_content)))
if isinstance(Bar(), Foo):
    print("foo")
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security