Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 308
zenpoy Avatar asked Nov 08 '25 14:11

zenpoy


2 Answers

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 >:(
like image 91
Kenan Banks Avatar answered Nov 10 '25 04:11

Kenan Banks


Use keyword arguments:

def add_to_db(name=None, names=None):
    if name:
        .....
    elif names:
        ....
    else:
        raise ValueError("Invalid arguments")

add_to_db(name='John')
add_to_db(names=['explicit', 'is', 'better'])
like image 33
georg Avatar answered Nov 10 '25 04:11

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!