Hi,
Thanks in advance for your effort and time
I’m trying to find if the input is list or not, and if it is not a list the python will convert into a list.
When I pass a input which is non list, it is converting into a proper list, but when I pass list, the python is converting the same list into another list. I have attached snip and code below
Python Code:
def tolist(obj):
result = input if isinstance(obj, list) else [obj]
return result
element = tolist(UnwrapElement(IN[0]))
OUT = element
1 Like
@siddhartharajendran9 ,
it works well with this snippet
# 🔑 function
def tolist(x):
if hasattr(x,'__iter__'): return x
else: return [x]
# 🎯 items
element = tolist(IN[0])
OUT = element
2 Likes
Working fine now, thank you so much
I think the first approach should work but input should be obj. I use it in my nodes as strings are iterable so believe the alt method might have issues there.
2 Likes
(following Gavin’s comment)
input
is a built-in function in Python - update to this
result = obj if isinstance(obj, list) else [obj]
@GavinCrump strings use the __getitem__
method to act as an iterable sequence so they return false true for hasattr("this is a string", "__iter__")
Edit @haganjake2 You are correct - TIL strings do have an __iter__
method
5 Likes
Annoyingly in CPython 3 it doesnt @Mike.Buttery.
Not as concise but if you want to make sure you account for strings being iterable you can add this:
def tolist(obj1):
if isinstance(obj1, str): return [obj1]
elif hasattr(obj1, "__iter__"): return obj1
else: return [obj1]
5 Likes
Not at my PC, but I think this is my method of choice for CPython list enforcement:
data = IN[0]
if data.__class__ != list: data = [data]
If I typed it correctly this works in CPython3 and IronPython2. Not sure abouit IronPython3 at the moment though.
1 Like
For info, hasattr(x, "__iter__")
is currently buggy with CPython3/PythonNet2 with some .Net object
an example
another solution (works for both engines)
4 Likes