Is ther a recursive version of inst_to_dict( ) ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ulty

I have a settings class that holds int and String settings.
Using inst__to__dict( ) works fine to turn this class into a dictionary to be saved to disc.
The problem is that my settings class also holds references to other sub-settings classes.

So when using inst_to_dict() I get a dictionary like this:

{ “@subpath”: ^“SettingsClass”, “@path”: “res://setting_class.gd”, “myType”: 8, “sub_settings”: { “input_setting”: < RefCounted#-9223371938288628696> } }

Does anyone know of a way to use inst_to_dict() recursively to get another dict instead of the reference ?

Same for the loading with dict_to_inst()

I know I can manually add a separate function in to my settings class to export it and its sub-settings to dictionaries, but this will take a lot of time since i have many different sub setting classes which in turn also have sub-sub-settings…

inst_to_dict( object, recursive = true ) would be ideal : )

:bust_in_silhouette: Reply From: jgodfrey

First, I think the answer is “no” - inst_to_dict() doesn’t currently have a way to convert nested classes. And, it looks like you’re not the first to ask about it. Here’s a related github issue:

That thread leads to a number of script-based solutions, including this:

func recursively_serialize_object(instance: Object) -> Dictionary:
	var dict := inst_to_dict(instance)

	for key in dict:
		var field = dict[key]
		
		if field is Object:
			dict[key] = recursively_serialize_object(field)
		elif field is Array:
			var new_array := []
			for entry in field:
				new_array.append(recursively_serialize_object(entry))
			dict[key] = new_array
			pass
		# else keep value

	return dict

Maybe that 1) does what you need or 2) can be made to do what you need.

And, note there are several other script-based solutions mentioned at the above link…