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)?
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 >:(
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With