Search code examples
pythonruby

Python Equivalent to Ruby 'is_a?'


I'm wondering is there a Python Equivalent to Ruby's 'is_a?' method?

> "".is_a? String
=> true

Info:

is_a?(class) → true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

Thank you.


Solution

  • It depends on exactly what part you want.

    If you want to know whether foo is an instance of class C or any of its subclasses, then:

    isinstance(foo, C)
    

    If you want to know whether foo is an instance of C and only C, then:

    type(foo) == C
    

    Broadly speaking, frequent use of things like isinstance(...) or type(...) is a code smell because it means duck typing is broken, and Python relies heavily on that sort of contract. See, e.g., isinstance considered harmful.