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.
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 .
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
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.
In python, to access array items refer to the index number. we will use the index operator ” [] “ for accessing items from the array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With