Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a variable can be unpacked

Say I have a variable x, which is of an unknown data type. I also have some random function foo. Now I want to do something along the following lines:

If x is a type that can be unpacked using **, such as a dictionary, call foo(**x). Else, if x is a type that can be unpacked using *, such as a tuple, call foo(*x). Else, just call foo(x).

Is there an easy way to check whether a type can be unpacked via either ** or *?

What I am currently doing is checking the type of x and executing something like:

if type(x) == 'dict':
    foo(**x)
elif type(x) in ['tuple','list', ...]:
    foo(*x)
else:
    foo(x)

But the problem is that I don't know the complete list of data types that can actually be unpacked and I'm also not sure if user defined data types can have a method that allows them to be unpacked.

like image 230
K. Mao Avatar asked Sep 13 '26 19:09

K. Mao


1 Answers

You could use try:

try:
    foo(**x)
except:
    try:
        foo(*x)
    except:
        foo(x)

Its kind of crude, and doesn't distinguish why the exception occurred (which might be mitigated by checking the type of exception), but eliminates the need to try and enumerate which types can be called which way.

like image 91
Scott Hunter Avatar answered Sep 15 '26 07:09

Scott Hunter