Background document close causing referencing issues

Hi all,

I’m collecting information on Revit model element counts. I am using Python to open up a list of .rvt files in the background, count the elements, then close the file and repeat. I am using this loop as a way to save on memory (as the Document.BackgroundOpen node opens all files at once).

The Python code is a mixture of Document.BackgroundOpen, Document.Close and some code I found on here about pulling elements from categories.

The problem is whenever in the code I put the “doc.Close(False)” line it causes referencing issues. (Refer the below pic).
This error occurs only when that line of code is in the for loop. If this line of code is deleted, it works perfectly (except for not closing the files). With that line of code in, I found out it’ll run up until the “if t1[z]:” line then flick that error about the referenced object.

Here is the Python code:

for i in items:
	doc = app.OpenDocumentFile(i)

	#elements grouped by category (group by key)
	t1, t2 = [], []
	for cat, bic in [(cat, bic) for cat in cats for bic in bics]:
		if cat == bic.ToString():

	elements, categories = [], []

	#check if sub list is empty
	for z in range(len(t1)):
		if t1[z]:



Any help is appreciated, thanks.

That’s most likely happening because you’re referencing elements from those closed documents and trying to return them back to the graph. Dynamo will automatically try to wrap those elements into the equivalent wrapper classes. At that point you’ll get a failure because the documents those elements originated from do not exist in memory any more.