I have a function designed for interactive usage that takes either a single "scalar" value as argument or an iterable. The output should match the input. Here is a toy example.
def func(x):
flag = False
if isinstance(x, int):
flag = True
x = (x,)
retval = tuple(i**2 for i in x)
return retval[0] if flag else retval
>>> func(5)
25
>>> func((1,2,3,4))
(1, 4, 9, 16)
Question: Is there a more convenient method to check whether the user provided a "scalar" or an iterable? I don't want to rely on checking the with isinstance
?
I tried with hasattr(x, '__iter__')
, but this return True
for "scalar" string input (not covered in the example here).