Search code examples
pythonlistcoding-styledynamic-typing

Dynamic typing design : is recursivity for dealing with lists a good design?


Lacking experience with maintaining dynamic-typed code, I'm looking for the best way to handle this kind of situations :

(Example in python, but could work with any dynamic-typed language)

def some_function(object_that_could_be_a_list):
     if isinstance(object_that_could_be_a_list, list):
          for element in object_that_could_be_a_list:
              some_function(element)
     else:
          # Do stuff that expects the object to have certain properties 
          # a list would not have

I'm quite uneasy with this, since I think a method should do only one thing, and I'm thinking that it is not as readable as it should be. So, I'd be tempted to make three functions : the first that'll take any object and "sort" between the two others, one for the lists, another for the "simple" objects. Then again, that'd add some complexity.

What is the most "sustainable" solution here, and the one that guarantee ease of maintenance ? Is there an idiom in python for those situations that I'm unaware of ? Thanks in advance.


Solution

  • Don't type check - do what you want to do, and if it won't work, it'll throw an exception which you can catch and manage.

    The python mantra is 'ask for forgiveness, not permission'. Type checking takes extra time, when most of the time, it'll be pointless. It also doesn't make much sense in a duck-typed environment - if it works, who cares why type it is? Why limit yourself to lists when other iterables will work too?

    E.g:

    def some_function(object_that_could_be_a_list):
        try:
            for element in object_that_could_be_a_list:
                some_function(element)
        except TypeError:
            ...
    

    This is more readable, will work in more cases (if I pass in any other iterable which isn't a list, there are a lot) and will often be faster.

    Note you are getting terminology mixed up. Python is dynamically typed, but not weakly typed. Weak typing means objects change type as needed. For example, if you add a string and an int, it will convert the string to an int to do the addition. Python does not do this. Dynamic typing means you don't declare a type for a variable, and it may contain a string at some point, then an int later.

    Duck typing is a term used to describe the use of an object without caring about it's type. If it walks like a duck, and quacks like a duck - it's probably a duck.

    Now, this is a general thing, and if you think your code will get the 'wrong' type of object more often than the 'right', then you might want to type check for speed. Note that this is rare, and it's always best to avoid premature optimisation. Do it by catching exceptions, and then test - if you find it's a bottleneck, then optimise.