2
\$\begingroup\$

I want to create a function that unpacks nested dataclasses and namedtuples (or a combination of both)


my attempt

I found this answer about how to unpack a named tuple, and i am simply extending it:

the unpack function

def unpack(obj):
    if isinstance(obj, dict):
        return {key: unpack(value) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [unpack(value) for value in obj]
    elif is_named_tuple_instance(obj):
        return {key: unpack(value) for key, value in obj._asdict().items()}
    elif is_data_class_instance(obj):
        return {key: unpack(getattr(obj, key)) for key in obj.__dataclass_fields__.keys()}
    elif isinstance(obj, tuple):
        return tuple(unpack(value) for value in obj)
    else:
        return obj

the is_data_class_instance function:

def is_data_class_instance(obj):
    data_class_attrs = {'__dataclass_fields__', '__dataclass_params__'}
    return set(dir(obj)).intersection(data_class_attrs) == data_class_attrs

side note, would this be acceptable type hints ?

from typing import NamedTuple, Any, NewType, Union

DataClass = NewType('DataClass', Any)
def unpack(obj: Union[DataClass, NamedTuple, Any]) -> Union[tuple, list, dict, Any]:
    ...
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.