ess3nt1al
ess3nt1al

Reputation: 19

Is there a way to check each passed argument's type in Python?

Let's say I have a function that takes any number of arguments. Is there a way, except loops, to check if each of those arguments is a list?

def func(*args):
    # check if all args are lists

I was trying any() and all() methods, but can't figure out if there is a way to use isinstance() and type() with them.

Upvotes: 1

Views: 660

Answers (4)

GeekyCoder
GeekyCoder

Reputation: 138

There are many variants of this question:

  1. How to determine the type of an object?
  2. How to get the class of an object?
  3. How to check the type of an instance?
  4. How to check the class of an instance?

In Python, the built-in functions type() and isinstance() help you determine the type of an object.

  1. type(object) – Returns a string representation of the object’s type.

  2. isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.

reference : Determining the type of an object

also check out this link for more details.

Upvotes: 0

MYK
MYK

Reputation: 2997

I like the answer above:

all_lists = all(isinstance(arg, list) for arg in args)

But note you can also do type hints in the newer versions of Python:

def func(*args:list):
    # check if all args are lists

and you get some type checking from tools like Mypy

Upvotes: 0

Jiří Baum
Jiří Baum

Reputation: 6930

all(isinstance(arg, list) for arg in args)

Of course, there's a loop hidden in the generator expression; at the end of the day, there has to be some kind of loop..

Upvotes: 0

luk2302
luk2302

Reputation: 57114

Sure thing:

all_lists = all(isinstance(arg, list) for arg in args)

Upvotes: 5

Related Questions