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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With