Type checking of arguments Python [duplicate]
Use isinstance()
. Sample:
if isinstance(n, unicode): # do thiselif isinstance(n, Node): # do that...
You can also use a try catch to type check if necessary:
def my_function(this_node): try: # call a method/attribute for the Node object if this_node.address: # more code here pass except AttributeError, e: # either this is not a Node or maybe it's a string, # so behavior accordingly pass
You can see an example of this in Beginning Python in the second about generators (page 197 in my edition) and I believe in the Python Cookbook. Many times catching an AttributeError
or TypeError
is simpler and apparently faster. Also, it may work best in this manner because then you are not tied to a particular inheritance tree (e.g., your object could be a Node
or it could be something other object that has the same behavior as a Node
).