from typing import Optional
from typing import Dict
from typing import Any


def exec_and_return(exec_str: str,
                    modules: Optional[Dict[str, Any]] = None) -> Any:
    """Execute the exec_str with :meth:`exec` and return the value

    Args:
        exec_str: The string to execute

    Returns:
        The value in the `exec_str`

    """
    ldict: Dict[str, Any] = {}
    if modules is not None:
        exec("testvar = " + exec_str, {**modules, **globals()}, ldict)
    else:
        exec("testvar = " + exec_str, globals(), ldict)
    retval = ldict['testvar']
    return retval