Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check if an object is NOT an "array-type"

I'm looking for a way to test if an object is not of a "list-ish" type, that is - not only that the object is not iterable (e.g. - you can also run iter on a string, or on a simple object that implements iter) but that the object is not in the list family. I define the "list" family as list/tuple/set/frozenset, or anything that inherits from those, however - as there might be something that I'm missing, I would like to find a more general way than running isinstance against all of those types.

I thought of two possible ways to do it, but both seem somewhat awkward as they very much test against every possible list type, and I'm looking for a more general solution.

First option:

return not isinstance( value, (frozenset, list, set, tuple,) )

Second option:

return not hasattr(value, '__iter__')

Is testing for the __iter__ attribute enough? Is there a better way for finding whether an object is not a list-type?

Thanks in advance.

Edit:

(Quoted from comment to @Rosh Oxymoron's Solution):
Thinking about the definition better now, I believe it would be more right to say that I need to find everything that is not array-type in definition, but it can still be a string/other simple object...
Checking against collections.Iterable will still give me True for objects which implement the __iter__ method.

like image 257
amito Avatar asked Aug 28 '11 13:08

amito


People also ask

How do you check if an object is a list type?

Use type() to check if an object has type list. Call type(object) to return the type of object . Use the is keyword to check if the type is list .

Is there an array type in Python?

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

What is Typecode in Python array?

Arrays in python behave very similar to lists but they have the same data type of values stored in it. The data type is specified at the array creation time by using a single character is called the type code.

How do you access an array of objects in Python?

In python, to access array items refer to the index number. we will use the index operator ” [] “ for accessing items from the array.


1 Answers

There is no term 'list-ish' and there is no magic build-in check_if_value_is_an_instance_of_some_i_dont_know_what_set_of_types.

You solution with not isinstance( value, (frozenset, list, set, tuple,) ) is pretty good - it is clear and explicit.

like image 198
Roman Bodnarchuk Avatar answered Nov 01 '22 14:11

Roman Bodnarchuk