In python, strings can be looped/iterated, as list, tuples, etc can be. We have the same for dict and bytes. So, using isinstance vs any collections.abc class gives True on list, bytes, dicts, etc.
I'm searching for an elegant way to check if I have received a list-like argument to a method: list, tuple, set, numpy array, pandas Series, etc?
Do you have any suggestion which is not test if iterable but neither string nor dict, etc.
I'm really trying to match the non-developer intuitive understanding of what a list is.
Another option would be checking if your variable is an Iterable, but manually exclude what you think should not be accepted:
from collections.abc import Iterable
excluded_types = (str, dict)
if isinstance(obj, Iterable) and not isinstance(obj, excluded_types):
do_something()
But you should define what iterable behavior you are expecting to consider something "list-like".
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