I run into the following two issues at the same time fairly frequently
- I have a function with an argument that's expected to be a container of strings
- I would like to simplify calls by passing the function either a container of strings or a single string that is not a singleton list
I usually handle this with something like the following, which seems somehow not pythonic to me (I don't know why). Is there a more pythonic way to handle the situation? Is this actually a bad habit and it's most appropriate to require function calls like my_func(['just_deal_with_it'])
?
Note the function iterable_not_string
below is from sorin's answer to another question
from collections.abc import Iterable
def iterable_not_string(x):
is_iter = isinstance(x, Iterable)
is_not_str = (not isinstance(x, str))
return (is_iter and is_not_str)
def my_func(list_or_string):
if iterable_not_string(list_or_string):
do_stuff(list_or_string)
else:
do_stuff([list_or_string])