Proper way to assert type of variable in Python Proper way to assert type of variable in Python python python

Proper way to assert type of variable in Python


The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):    "Print 'text' in UPPER between 'begin' and 'end' in lower"    try:      print begin.lower() + text.upper() + end.lower()    except (AttributeError, TypeError):      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)


You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):    "Print text in UPPER between 'begin' and 'end' in lower."    for obj in (text, begin, end):        assert isinstance(obj, str), 'Argument of wrong type!'    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?


Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: passprint isinstance(MyClass(), MyClass) # -> Trueprint isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.