0

I was wondering what the most pythonic way would be to check if a function input is a string or a list. I want the user to be able to enter a list of strings or a string itself.

def example(input):

   for string in input:

       #Do something here.
       print(string)

Obviously this will work in the input is a list of strings but not if the input is a single string. Would the best thing to do here is add type checking in the function itself?

def example(input):

    if isinstance(input,list):
       for string in input:
           print(input)
           #do something with strings
    else:
        print(input)
        #do something with the single string

Thanks.

6
  • 1
    So what's wrong with your second approach? Commented Mar 5, 2019 at 10:40
  • Your second approach seems to be fine. Commented Mar 5, 2019 at 10:42
  • The second approach is how I would do it. Commented Mar 5, 2019 at 10:42
  • Use cases for polymorphic functions like this can accept different types are rare, but what you're doing is fine Commented Mar 5, 2019 at 10:45
  • There is nothing wrong with the second approach, I was just wondering if it is the best style to deal with these kind of problems. Commented Mar 5, 2019 at 10:45

2 Answers 2

0

The second approach is fine, except that it should do with print(string_) and not print(input), if it matters:

def example(input):
    if isinstance(input,list):
       for string_ in input:
           print(string_)
           #do something with strings
    else:
        print(input)
        #do something with the single string


example(['2','3','4'])
example('HawasKaPujaari')

OUTPUT:

2
3
4
HawasKaPujaari
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry yeah this is correct it was a typo in my original code. As long as this type checking of the list is considered alright style wise I'm happy enough.
0

Your code is fine. However you mentioned the list should be a list of strings:

if isinstance(some_object, str):
    ...
elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

Check if input is a list/tuple of strings or a single string

4 Comments

How is this better than OP's second approach ?
Forgot to tell his code is fine. However he mentioned the list should be a list of strings.
Should you add this much checking into code?
This is up to you, if it is necessary for you to check if the list is actually a list of strings yes, definitely. If somehow you're sure it is, it just becomes an almost useless double-check.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.