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 ofiftype(Foo())==Foo:print("is foo")
Compliant Code Examples
raiseValueError("target %s config %s has type of %s"%(target,config_content,type(config_content)))
ifisinstance(Bar(),Foo):print("foo")
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- python-best-practices # Rules to enforce Python best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines