0

Currently I'm focussing on the pythonic way of writing my code and I ran into two situations where I wonder what's best.

First the situation for method overloading, which is not available in python. How would I best solve the situation where I have a function that fetches data from a database, however depending on an argument being an integer or a list of integers the query would be different. Example:

def getData(ids):
    if type(ids) == int:
        # query the database in an efficient manner for a single ID
    elif type(ids) is list:
        # query the database in a different manner efficiently for multiple ID's
        # also return the data differently

Would I do all the work in a single function or do I use different functions which are called from the above function to do the work? Or would I just need to call a different function explicitly depending on whether I have a list of ID's or just a single ID? What do you believe is best?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Yorian
  • 2,002
  • 5
  • 34
  • 60
  • 2
    Avoid "which do you prefer" questions, as those are opinion based, and are often closed as such. Make questions as objective as possible. – Carcigenicate Sep 06 '17 at 12:35
  • 1
    And personally, for your first question, I think it makes more sense to make each "branch" it's own function. Have a getByID, and getByMultipleID function. Then, if you want to smooth its usage, have a getData function that decides which to use. Separating the decision logic from the "get"ting logic should make for cleaner code. – Carcigenicate Sep 06 '17 at 12:37
  • 1
    I'm nominating this question for reopening now that it has been edited. But in this case, it should be a duplicate of "how to pass an integer or a list/iterable" to a same function and to detect args. John answer suits me, though. – Jean-François Fabre Sep 06 '17 at 12:44
  • If the return value is also different (ie a single list in the first case and a list of lists or dict of lists in the second) then it should really be two distinct functions. Else, it's indeed a "how to pass an integer or a list/iterable" duplicate. – bruno desthuilliers Sep 06 '17 at 13:13
  • https://stackoverflow.com/a/24602374/5320906 is an example of using `functools.singledispatch` with instance methods to do this, if you are using python 3.4 or later. – snakecharmerb Sep 09 '17 at 09:20

1 Answers1

1

Use isinstance:

import collections

def getData(ids):
    if isinstance(ids, collections.Iterable):
        # query the database efficiently for multiple ID's
    else:
        # query the database in an efficient manner for a single ID
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    not sure it answers, but it's helpful. careful, though, if a string is passed, then it's seen as iterable. the intent is probably to check lists but also sets, dicts... – Jean-François Fabre Sep 06 '17 at 12:44