from typing import Any
import re
import importlib


def load_code(c: str) -> Any:
    """
    Deserializes an object from a Python code string.

    Parameters
    ----------
    c
        A string representing the object as Python code.

    Returns
    -------
    Any
        The deserialized object.

    See Also
    --------
    dump_code
        Inverse function.
    """

    def _load_code(code: str, modules=None):
        if modules is None:
            modules = {}
        try:
            return eval(code, modules)
        except NameError as e:
            m = re.match(r"name '(?P<module>.+)' is not defined", str(e))
            if m:
                name = m["module"]
                return _load_code(
                    code,
                    {**(modules or {}), name: importlib.import_module(name)},
                )
            else:
                raise e
        except AttributeError as e:
            m = re.match(
                r"module '(?P<module>.+)' has no attribute '(?P<package>.+)'",
                str(e),
            )
            if m:
                name = m["module"] + "." + m["package"]
                return _load_code(
                    code,
                    {**(modules or {}), name: importlib.import_module(name)},
                )
            else:
                raise e
        except Exception as e:
            raise e

    return _load_code(c)