0

I am writing a method that can take in a scalar or a list of items. The first thing that I want to do in the method is to ensure that I am working with a list. I want to know the most pythonic way of doing that. Currently I am doing:

def print_item_or_list(list_or_item):
    if not isinstance(list_or_item, (list, tuple)):
        list_or_item = [list_or_item]

    # Now I can consistently work with an iterable
    for item in list_or_item:
         print item

Is there a more idiomatic way?

Thanks!

Jonathan
  • 16,077
  • 12
  • 67
  • 106

3 Answers3

2

Usually the way its done in Python (or the way I've done it) is to use simply use the variable as a list, then handle the error. This can be done with try...except block as show below:

def tryExceptExample(data):

    try:
        for a in data:    #or whatever code you want to run
            print a

    except TypeError:
        print "Invalid data"   #code you want to run if code in try block fails

    finally:
        print "fin"    #optional branch which always runs

Sample Output:

>>> tryExceptExample([1,2,3])
1
2
3
fin
>>> tryExceptExample("abcd")
a
b
c
d
fin
>>> tryExceptExample(5)
Invalid data
fin

Some Things to Note:

  • The code in the try branch will run until it hits an error, then immediatly proceed to except, meaning all lines before an error execute. For this reason, try to keep the number of lines in this branch to a minimum

  • Here the except branch is shown with a TypeError. This means only TypeErrors will be "caught" by this branch and any other errors will be thrown normally. You can have as many except branches as needed for as many errors as you want to catch. You can also have a "bare" except branch which will catch all errors, but this is considered poor form and non-pythonic

wnnmaw
  • 5,444
  • 3
  • 38
  • 63
1

as Wooble says, your function is not idiomatic in the first place. consider:

def print_one_item(the_item):
    return print_many_items([the_item])

def print_many_items(the_items):
    for an_item in the_items:
        ...
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
0

you can type() function as in

if type(some_list) is not list:
    handle
Apoorv
  • 373
  • 1
  • 5
  • 15
  • 2
    In general I believe `isinstance` is preferred because it is able to handle inheritance. –  Aug 26 '14 at 12:53