Python: How to define a function that gets a list of strings OR a string

python

Solution

I think your best bet is to cast a single string to a 1-element list, and then have the rest of your function deal exclusively with lists.

def add_to_db(name_or_names):
    import types
    if isinstance(name_or_names, types.StringTypes):
        name_or_names = [name_or_names]
    try:
        for name in name_or_names:
            add_name(name)
        commit_to_db()
    except TypeError:
            # we didn't get a string OR a list >:(

Problem

Let's say I want to add a list of strings or just one to a DB: ``` names = ['Alice', 'Bob', 'Zoe'] ``` and I want that `add_to_db` will accept both cases ``` add_to_db(names) add_to_db('John') ``` Is this the correct way to go: ``` def add_to_db(name_or_names): if (...): ... # add a single name else: for name in name_or_names: ... # add a single name commit_to_db() ``` What should I put in the first `...`, as condition to whether it's a list of strings or just a string (don't forget that string is also iterable)?

Original source

Related problems