#!/usr/bin/env python """Python type checking Simple illustration of all the various kinds of type-checking you can do in Python. """ import types def type_check_1(x): """Return the square of an integer Raise a TypeError if the argument is not an integer. """ if not type(x) == types.IntType: raise TypeError, "%s is not an integer" % x return x**2 def type_check_1(x): """Return the square of an integer Raise a TypeError if the argument is not an integer. """ if not type(x) == type(53): raise TypeError, "%s is not an integer" % x return x**2 # Here is a very basic object hierarchy. # # object # | # / \ # / \ # A C # | # | # B class A(object): pass class B(A): pass class C(object): pass if __name__ == "__main__": # Pass in the correct argument type. print type_check_1(4) # 16 # Pass in an invalid argument type. try: type_check_1([53, 'mouse', 3+2j]) except TypeError, e: print e # Prints the exception # Illustration of object hierarchy. a = A() b = B() c = C() print type(a) # print type(b) # print type(c) # print isinstance(a, A) # True print isinstance(b, B) # True print isinstance(c, C) # True print isinstance(b, A) # True print isinstance(c, A) # False print issubclass(B, A) # True print issubclass(C, A) # False print issubclass(A, object) # True print issubclass(A, B) # False