Per this thread on the Dynamo forums: http://dynamobim.org/forums/topic/how-to-handle-variable-list-lengthnesting-in-custom-nodes-python/, I'd like to find a way to handle variable inputs for a custom node.
Here's an example script that changes the family type of an element:
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# Import ToDSType(bool) extension method
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
from System.Collections.Generic import *
# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application
doc = DocumentManager.Instance.CurrentDBDocument
app = DocumentManager.Instance.CurrentUIApplication.Application
inputItems = []
for i in IN[0]:
inputItems.append(UnwrapElement(i))
toggle = IN[1]
familyType = UnwrapElement(IN[2]).Id
elementlist = []
TransactionManager.Instance.EnsureInTransaction(doc)
if toggle == True:
for item in inputItems:
item.ChangeTypeId(familyType)
elementlist.append(item)
else:
None
TransactionManager.Instance.TransactionTaskDone()
OUT = elementlist
I'd like to find a way that I can handle an input that is a list, a nested list, OR a single item (non-list) like the image below:
For the latter two, I can just use a list.flatten. The problem is finding a way to handle all three types of lists/elements.
Thoughts?
In this case if your goal is to use Python to handle all different input structures I would suggest something like this:
if you only want to perform an operation on an item (let's say add +1) regardless of the data structure, I use recursion and a simple isinstance (IN[0], list)
check like so:
#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN
def ProcessList(_func, _list):
return map( lambda x: ProcessList(_func, x) if type(x)==list else _func(x), _list )
def AddOne(item):
return item + 1
if isinstance (IN[0], list):
output = ProcessList(AddOne, IN[0])
else:
output = AddOne(IN[0])
#Assign your output to the OUT variable.
OUT = output
Here's an example in Dynamo operating on different structures of data:
This approach is pretty good because it allows you to output the exact same structure as was inputted. I use this a lot.