Type Checking Examples


Type Checking Examples

This document introduces type() and isinstance() usage.

Module Introduction

Supports type(obj) to get type, isinstance(obj, class) to check instance relationship. Built-in example:

#!pika
assert type(1) == int
assert isinstance('a', str)
#!pika

Example Code

type Function (type.py)

#!pika
class Test1:
    def test(self):
        return 'test 1'


class Test2:
    def test(self):
        return 'test 2'

t1 = Test1()
tt1 = type(t1)
ttt1 = tt1()

t2 = Test2()
tt2 = type(t2)
ttt2 = tt2()

assert ttt1.test() == 'test 1'
assert ttt2.test() == 'test 2'
assert type(ttt1) == Test1
assert type(ttt2) == Test2
assert type(ttt1) != type(ttt2)
assert type(ttt1) != Test2
assert type(ttt2) != Test1

print('PASS')
#!pika

Note: type(instance) gets class object, which can be called again to create new instances; use == to compare if types are the same.

isinstance Check (isinstance.py)

#!pika
# Testing with builtin types
assert isinstance(10, int) == True
assert isinstance("Hello, world!", str) == True
assert isinstance([1, 2, 3, 4, 5], list) == True
assert isinstance({"key": "value"}, dict) == True
assert isinstance(3.14, float) == True
assert isinstance(object(), object) == True
assert isinstance(10, str) == False

class MyClass:
    pass

class BaseClass(object):
    def __init__(self):
        self.a = 1

class DerivedClass(BaseClass):
    def __init__(self):
        super().__init__()
        self.b = 2

base_instance = BaseClass()
derived_instance = DerivedClass()

# Instances of DerivedClass should also be instances of BaseClass
assert isinstance(MyClass(), object) == True
assert isinstance(base_instance, object) == True
assert isinstance(base_instance, BaseClass) == True
assert isinstance(derived_instance, BaseClass) == True

# However, instances of BaseClass are not instances of DerivedClass
assert isinstance(base_instance, DerivedClass) == False

# And instances of DerivedClass are, of course, instances of DerivedClass
assert isinstance(derived_instance, DerivedClass) == True

print('PASS')
#!pika

Note: isinstance(obj, Class) works for both built-in types and inheritance relationships, derived class instances return True for base class.

isinstance Usage in Logic Branches (issue_isinstance.py)

#!pika
class scr_Text:
    def cus_print(self, data, end='\n'):
        str_buf = ""

        if isinstance(data, str):
            str_buf = str_buf + data
        elif isinstance(data, int):
            str_buf = str_buf + str(data)
        else:
            str_buf = "The type is not recognized"
        str_buf = str_buf + end


screen = scr_Text()
screen.cus_print(12)
screen.cus_print(12)
screen.cus_print(12)
screen.cus_print(12)

print('PASS')
#!pika

Note: Use isinstance to branch and handle different data types, implementing simple polymorphism or formatted output.

Notes

  • Using type(x) == Type only checks exact type, not including subclasses; for inheritance consideration, better to use isinstance(x, Type).
  • In OPBTPython, built-in types are consistent with PikaPython documentation, behavior may have minor differences from CPython.