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

Time:11-03

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.

CodePudding user response:

Sure thing:

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

CodePudding user response:

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..

CodePudding user response:

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

CodePudding user response:

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.

  • Related