pythontypechecking

Type checking of arguments


Sometimes checking of arguments in Python is necessary. e.g. I have a function which accepts either the address of other node in the network as the raw string address or class Node which encapsulates the other node's information.

I use type function as in:

    if type(n) == type(Node):
        do this
    elif type(n) == type(str)
        do this

Is this a good way to do this?


Solution

  • Use isinstance(). Sample:

    if isinstance(n, unicode):
        # do this
    elif isinstance(n, Node):
        # do that
    ...