from typing import Any
from typing import Union
from typing import List


def to_dict(obj: Any) -> dict:
    """Converts class instances to dictionaries.
    Handles nested objects as well."""
    if not hasattr(obj, "__dict__"):
        return obj
    result: dict = {}
    for key, val in obj.__dict__.items():
        element: Union[List[Union[dict, List[dict]]], dict] = []
        if not key.startswith("__"):
            if isinstance(val, list) and isinstance(element, list):
                for item in val:
                    element.append(to_dict(item))
            else:
                element = to_dict(val)
        result[key] = element
    return result