Regis May
Regis May

Reputation: 3466

How to check if a variable contains a type or a list of types?

I'd like to pass a type or a list of types as an argument to a function. But within the function I need to distinguish between the type and the list of types. Roughly explained I need some kind of branching like this:

if //someVar is a type//:
    ....
elif isinstance(someVar, list):
    for t in list:
        if //t is a type//:
            ....
        else:
            print("ERROR")
else
    print("ERROR")

Types can either be some "primitive" like int or str but also tuples or classes as well.

The question: How can I correctly and efficiently distinguish between types and list of types?

Upvotes: 0

Views: 121

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160667

You'll need to provide a tuple to isinstance containing the types you think are appropriate as "primitive". For lists you'll just pass a list.

If you need to handle "classes as well" you'll need to explicitly add those classes in the tuple since there is no ClassType in Python (at least in Python 3, in Python 2 old-style classes had a common type).

So, given an example class Bar, here's how you would allow str, ints, tuples and Bar as "primitive" while further checking for lists:

class Bar: pass

def foo(arg):
    if isinstance(arg, (int, str, tuple, Bar)):
        print("type str or int or tuple or Bar")
    elif isinstance(arg, list):
        print("a list")
    else:
        print("Error")

Function foo now makes these distinctions for you:

>>> foo(1)
type str or int or tuple or Bar
>>> foo([1])
a list
>>> foo(Bar())
type str or int or tuple or Bar
>>> foo(foo)
Error

further branching in the elif clause for lists is similarly performed.

Upvotes: 1

Related Questions