is_namedtuple

privex.helpers.collections.is_namedtuple(*objs)bool[source]

Takes one or more objects as positional arguments, and returns True if ALL passed objects are namedtuple instances

Example usage

First, create or obtain one or more NamedTuple objects:

>>> from collections import namedtuple

>>> Point, Person = namedtuple('Point', 'x y'), namedtuple('Person', 'first_name last_name')

>>> pt1, pt2 = Point(1.0, 5.0), Point(2.5, 1.5)
>>> john = Person('John', 'Doe')

We’ll also create a tuple, dict, and str to show they’re detected as invalid:

>>> normal_tuple, tst_dict, tst_str = (1, 2, 3,), dict(hello='world'), "hello world"

First we’ll call is_namedtuple() with our Person NamedTuple object john:

>>> is_namedtuple(john)
True

As expected, the function shows john is in-fact a named tuple.

Now let’s try it with our two Point named tuple’s pt1 and pt2, plus our Person named tuple john.

>>> is_namedtuple(pt1, john, pt2)
True

Since all three arguments were named tuples (even though pt1/pt2 and john are different types), the function returns True.

Now we’ll test with a few objects that clearly aren’t named tuple’s:

>>> is_namedtuple(tst_str)   # Strings aren't named tuples.
False
>>> is_namedtuple(normal_tuple)    # A plain bracket tuple is not a named tuple.
False
>>> is_namedtuple(john, tst_dict)  # ``john`` is a named tuple, but a dict isn't, thus False is returned.
False

Original source: https://stackoverflow.com/a/2166841

Parameters

objs (Any) – The objects (as positional args) to check whether they are a NamedTuple

Return bool is_namedtuple

True if all passed objs are named tuples.