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")
シームレスな統合。 Datadog Code Security をお試しください
Datadog Code Security
このルールを試し、Datadog Code Security でコードを解析する
このルールの使用方法
1
2
rulesets:- python-best-practices # Rules to enforce Python best practices.