Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python force input to be a list

Tags:

python

list

Is there a way I can elegantly cast function inputs into a list? While ensuring that if the input is already a list, it is kept at a top level list?

For instance:

def pprint(input):
    for i in input:
        print(i)

a = ['Hey!']
pprint(a) # >>>>'Hey!'

b = 'Hey!'
pprint(b) # >>>> 'H', 'e', 'y', '!'  # NOT WANTED BEHAVIOR

My current way around this is to do a type check, which is not very pythonic nor elegant. Is there a better solution?

# possible solution 1
def pprint2(input):
    if type(input) not in [list, tuple]:
        input = [input]
    for i in input:
        print(i)

# possible solution 2
      # but I would really really like to keep the argument named! (because I have other named arguments in my actual function), but it does have the correct functionality!
def pprint3(*args):
    for i in input:
        print(i)
like image 681
user1639926 Avatar asked Mar 28 '26 13:03

user1639926


1 Answers

Use isinstance and collections.Iterable:

from collections import Iterable
def my_print(inp):
    #As suggested by @user2357112
    if not isinstance(inp, Iterable) or isinstance(inp, basestring):
        inp = [inp]                           #use just `str` in py3.x
    for item in inp:  #use `yield from inp` in py3.x                     
        yield item
...         
>>> for x in my_print('foo'):
...     print x
...     
foo
>>> for x in my_print(range(3)):
    print x
...     
0
1
2
>>> for x in my_print(dict.fromkeys('abcd')):
    print x
...     
a
c
b
d

Note that pprint is name of standard module in python, so I'd suggest you to use a different variable name.

like image 93
Ashwini Chaudhary Avatar answered Mar 30 '26 03:03

Ashwini Chaudhary