42

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?

Update 1: Python 3 has annotation for function parameters. These can be used for type checks using tool: http://mypy-lang.org/

4

5 Answers 5

120

Use isinstance(). Sample:

if isinstance(n, unicode):
    # do this
elif isinstance(n, Node):
    # do that
...
4
  • 4
    isinstance() also checks for subclasses.
    – AKX
    Apr 9, 2009 at 14:02
  • isinstance(n, unicode) won't match plain str objects in python 2.x. Compare against basestring instead, which matches either str or unicode: isinstance(n, basestring) Apr 9, 2009 at 14:15
  • 2
    wiki.python.org/moin/… - Part of first paragraph states: In Python, it's the program's responsibility to use built-in functions like isinstance() and issubclass() to test variable types and correct usage. Python tries to stay out of your way while giving you all you need to implement strong type checking. Aug 9, 2012 at 5:09
  • 20
    +1 to make up for @nosklo's -1. I don't think its cool to -1 people because they don't agree in implementation concepts with you. There are many instances where typechecking is the right thing to do, specially since its a way of overloading a function. This is particularly useful when designing an API to make sure that users do the right thing. Oct 18, 2012 at 19:42
17
>>> isinstance('a', str)
True
>>> isinstance(n, Node)
True
1
  • 4
    well , type checking is a must in my app. I use OleFileIO_PL and it returns item list in a nested list . if the item is a directory type , it is a list inside nested list , if it a file then its a string. Without checking string or not , it gonna be impossible use. Sep 22, 2011 at 20:20
7

Sounds like you're after a "generic function" - one which behaves differently based on the arguments given. It's a bit like how you'll get a different function when you call a method on a different object, but rather than just using the first argument (the object/self) to lookup the function you instead use all of the arguments.

Turbogears uses something like this for deciding how to convert objects to JSON - if I recall correctly.

There's an article from IBM on using the dispatcher package for this sort of thing:

From that article:

import dispatch
@dispatch.generic()
def doIt(foo, other):
    "Base generic function of 'doIt()'"
@doIt.when("isinstance(foo,int) and isinstance(other,str)")
def doIt(foo, other):
    print "foo is an unrestricted int |", foo, other
@doIt.when("isinstance(foo,str) and isinstance(other,int)")
def doIt(foo, other):
    print "foo is str, other an int |", foo, other
@doIt.when("isinstance(foo,int) and 3<=foo<=17 and isinstance(other,str)")
def doIt(foo, other):
    print "foo is between 3 and 17 |", foo, other
@doIt.when("isinstance(foo,int) and 0<=foo<=1000 and isinstance(other,str)")
def doIt(foo, other):
    print "foo is between 0 and 1000 |", foo, other
3
  • 3
    This is uglier and less maintainable than just hacking it out with typechecking IMO; an attempt to graft overloaded functions onto a language where it just doesn't fit very well.
    – bobince
    Apr 9, 2009 at 17:55
  • I like the feature of c++ of function overloading which seems to be possible with this approach. I think it makes the code more readable since you don't have to check the arguments for certain types or values. Nice posting!
    – Woltan
    Feb 8, 2011 at 8:43
  • In c++ these are the overloaded functions: void do(Node& n); void do(string n);
    – JayS
    Dec 21, 2018 at 15:14
6

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).

3
  • +1: attribute checking won't hurt code reuse, so it is better than typechecking, although having a function with different behaviours based on types is not a good idea.
    – nosklo
    Apr 9, 2009 at 17:03
  • 3
    As long as the different behaviours are similar (at least in concept), I don't see what the big deal is. We all seem to think that it's OK for + (a.k.a. operator+() in C++) to work on numbers or strings, yet it actually has different behaviours based on types.
    – RobH
    Apr 9, 2009 at 17:24
  • In my example, the + operator is, of course, implemented by two different functions that overload the operator. Unfortunately, since variables in Python are not typed, you can't overload functions based solely on type.
    – RobH
    Apr 9, 2009 at 17:28
4

No, typechecking arguments in Python is not necessary. It is never necessary.

If your code accepts addresses as rawstring or as a Node object, your design is broken.

That comes from the fact that if you don't know already the type of an object in your own program, then you're doing something wrong already.

Typechecking hurts code reuse and reduces performance. Having a function that performs different things depending on the type of the object passed is bug-prone and has a behavior harder to understand and maintain.

You have following saner options:

  1. Make a Node object constructor that accepts rawstrings, or a function that converts strings in Node objects. Make your function assume the argument passed is a Node object. That way, if you need to pass a string to the function, you just do:

    myfunction(Node(some_string))
    

    That's your best option, it is clean, easy to understand and maintain. Anyone reading the code immediatelly understands what is happening, and you don't have to typecheck.

  2. Make two functions, one that accepts Node objects and one that accepts rawstrings. You can make one call the other internally, in the most convenient way (myfunction_str can create a Node object and call myfunction_node, or the other way around).

  3. Make Node objects have a __str__ method and inside your function, call str() on the received argument. That way you always get a string by coercion.

In any case, don't typecheck. It is completely unnecessary and has only downsides. Refactor your code instead in a way you don't need to typecheck. You only get benefits in doing so, both in short and long run.

22
  • 24
    If neither Node nor str is your own implementation (and they probably aren't here), you don't get to add methods like str to support your alternative behaviours(*). In this case, typechecking is an obvious and acceptable choice, preferable to having to wrap every str instance.
    – bobince
    Apr 9, 2009 at 17:52
  • 42
    It is mostly never necessary... not never. If you are using python to define a remote interface (eg: XMLRPC), strong type-checking at the interface can be a good idea, even if only to stop RPC callers who are using strongly typed languages (and mindsets) from having their brains/tempers explode.
    – Russ
    Jun 25, 2011 at 18:13
  • 16
    @nosklo: You go around on every other question saying "-1 - No mention that type checking is a bad idea". But in your case, -1 for no mention about where it is officially a bad idea to do type checking. This sounds more like an opinion, or drawing on some other language concept. It seems others are pointing out official statements that support the act of type checking.
    – jdi
    Oct 18, 2012 at 19:36
  • 27
    This is a very subjective response, I'm surprised it was accepted as the answer. Looking for answer? Look at answer below Type checking/enforcement can be immensely useful when working with larger non-trivial Object Oriented systems with objects (... of very specific types) communicating with one another. While I don't advocate type checking built-in types (list, str, etc..), allowing classes/objects to use/depend on defined behavior of other classes/objects is OOP 101. IMHO Writing off all type checking as "bad practice" simply restricts your abilities/power as an OOP programmer.
    – Erik Aybar
    Oct 7, 2014 at 12:58
  • 29
    Very unnecessary snarky tone in this answer. This is an opinion and included a lot of emotional baggage as well. Oct 3, 2015 at 17:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.