Skip to content

pandas_utils

langroid/utils/pandas_utils.py

UnsafeCommandError

Bases: ValueError

Raised when a command string violates security policy.

CommandValidator(df_name='df')

Bases: NodeVisitor

AST walker that enforces the security policy.

Source code in langroid/utils/pandas_utils.py
def __init__(self, df_name: str = "df"):
    self.df_name = df_name
    self.depth = 0
    self.chain = 0

sanitize_command(expr, df_name='df')

Validate expr; return it unchanged if it passes all rules, else raise UnsafeCommandError with the first violation encountered.

Source code in langroid/utils/pandas_utils.py
def sanitize_command(expr: str, df_name: str = "df") -> str:
    """
    Validate *expr*; return it unchanged if it passes all rules,
    else raise UnsafeCommandError with the first violation encountered.
    """
    tree = ast.parse(expr, mode="eval")
    CommandValidator(df_name).visit(tree)
    return expr

safe_eval_globals(local_vars)

Return a globals dict for :func:eval with __builtins__ restricted to a safe read-only set, so that bare names such as __import__, eval, exec and open do not resolve via Python's implicit builtin injection.

This is defence in depth for expressions that have already passed :func:sanitize_command. It is not a sandbox on its own and does not make an unvalidated (full_eval=True) expression safe; see SECURITY.md.

Parameters:

Name Type Description Default
local_vars Dict[str, Any]

User-provided variables to expose to the eval'd expression (e.g. {"df": <DataFrame>}).

required

Returns:

Type Description
Dict[str, Any]

A new dict suitable as the globals argument of eval().

Source code in langroid/utils/pandas_utils.py
def safe_eval_globals(local_vars: Dict[str, Any]) -> Dict[str, Any]:
    """Return a globals dict for :func:`eval` with ``__builtins__`` restricted
    to a safe read-only set, so that bare names such as ``__import__``,
    ``eval``, ``exec`` and ``open`` do not resolve via Python's implicit
    builtin injection.

    This is defence in depth for expressions that have already passed
    :func:`sanitize_command`. It is not a sandbox on its own and does not make
    an unvalidated (``full_eval=True``) expression safe; see SECURITY.md.

    Args:
        local_vars: User-provided variables to expose to the eval'd
            expression (e.g. ``{"df": <DataFrame>}``).

    Returns:
        A new dict suitable as the ``globals`` argument of ``eval()``.
    """
    return {**local_vars, "__builtins__": _SAFE_BUILTINS}