Metadata

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

Language: Python

Severity: Notice

Category: Best Practices

Description

Using type checks if an object o is exactly a given type. In contrast, isinstance checks if o is a given type, or any subclass of the given type, thus supporting inheritance. In addition,isinstance is generally faster than type.

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