> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/codesafe-package-documentation/codesafe-reference/codesafe-functions.md).

# CodeSafe Functions

**Available functions:**

* [`safe_eval`](#safe-eval)`(expr, allowed_builtins, allowed_vars, timeout=5, restricted_imports, allowed_function_calls, allow_attributes=False, immediate_termination=True, file_access=False, network_access=False)`: Evaluate an expression safely.
* [`encrypt_to_file`](#encrypt-to-file)`(code, output_file=None, mapping=default)`: Encrypt code in a file.
* [`run`](#run)`(encrypted_source: Union[str, IO], mapping=default)`: Decrypt and execute the Python code embedded in the specified file or stream.
* [`decrypt_to_file`](#decrypt-to-file)`(encrypted_file: Union[str, IO], output_file=None, mapping=default)`: Decrypt an encrypted file to a new file.
* [`encrypt`](#encrypt)`(code, mapping=default)`: Encrypt code, and return it.
* [`decrypt`](#decrypt)`(encrypted_code, mapping=default)`: Decrypt the code, and return it.
* [`EvaluationTimeoutError`](#exceptions): Exception raised when evaluation exceeds the timeout.
* [`UnsafeExpressionError`](#exceptions): Exception raised when an unsafe expression is detected.

***

### Safe eval

Evaluate an expression safely within a controlled sandbox environment.

```python
Parameters:
        expr (str): The expression to evaluate.
        allowed_builtins (dict, optional): A dictionary of allowed built-in functions.
        allowed_vars (dict, optional): A dictionary of allowed variables and functions.
        timeout (float, optional): Time limit for evaluation in seconds. Defaults to 5.
        restricted_imports (list, optional): A list of restricted imports or modules.
        allowed_function_calls (list, optional): A list of allowed function names to call.
        allow_attributes (bool, optional): Whether to allow access to safe attributes and methods (e.g., 'str.upper()'). Defaults to False.
        immediate_termination (bool, optional): Whether to forcibly terminate the evaluation if it exceeds the timeout. Defaults to True.
        file_access (bool, optional): Whether to allow file access (open, etc.). Defaults to False.
        network_access (bool, optional): Whether to allow network access (requests, etc.). Defaults to False.

Returns:
        object: The result of the evaluated expression.

Raises:
        EvaluationTimeoutError: If the evaluation exceeds the allowed time.
        ValueError: If the expression contains unsafe operations.
        UnsafeExpressionError: If restricted imports or unsafe nodes are detected in the AST.
        SyntaxError: If the expression contains invalid syntax.
```

#### Function arguments:

`expr`: An expression to evaluate.

`allowed_builtins`: A dictionary object of allowed built-in functions. `builtins = {"abs": abs, "max": max}`. In v0.0.5+, only explicitly whitelisted builtins are allowed, and dangerous functions like `exec`, `eval`, `compile`, and `__import__` are excluded by default.

`allowed_vars`: A dictionary object of allowed variables and functions. `{"x": 10, "y": 20, "custom_sum": custom_sum, "long_running_function": long_running_function, "sleep": sleep}`. For custom functions, other functions like **time.sleep**, and other variables in your code.

`timeout`: The evaluation limit for the call defaults to `5 seconds`.

`restricted_imports`: A list of restricted imports or modules. `['os', 'sys']`.

`allowed_function_calls`: A list of allowed function calls. Even when **allowed\_vars** contains the function, it is not callable unless passed to this parameter as well. `['custom_sum', 'max', 'abs', 'long_running_function', 'sleep']`. In v0.0.5+, only `ast.Name` targets are allowed for function calls; indirect calls via subscript, attribute, or other means are blocked.

`allow_attributes`: A bool that controls whether to allow access to safe attributes and methods (e.g., 'str.upper()').

`immediate_termination`: A bool that controls whether to forcibly terminate an evaluation if it exceeds the timeout; otherwise, the evaluation will continue until it is finished.

`file_access`: A bool that controls file access, and allows or disallows access to the filesystem. It restricts additional functions and modules from being called. Defaults to `False`.

`network_access`: A bool that controls internet access, and allows or disallows access to network, sockets, requests, and other libraries. Defaults to `False`.

{% hint style="warning" %}
**Security Note (v0.0.5+)**: The `safe_eval()` function now blocks all indirect function calls (e.g., `__builtins__['exec']()`, `getattr(__builtins__, 'exec')`). Only explicitly whitelisted function names passed via `allowed_function_calls` can be invoked. This prevents sandbox escape vulnerabilities present in versions 0.0.1-0.0.4.
{% endhint %}

### Exceptions

CodeSafe provides two custom exception classes for error handling:

**EvaluationTimeoutError**: Raised when the evaluation exceeds the specified timeout period.

```python
from codesafe import safe_eval, EvaluationTimeoutError

try:
    result = safe_eval("long_running_function()", timeout=2, allowed_function_calls=['long_running_function'])
except EvaluationTimeoutError:
    print("Evaluation timed out!")
```

**UnsafeExpressionError**: Raised when the expression contains unsafe operations, restricted imports, or blocked AST nodes.

```python
from codesafe import safe_eval, UnsafeExpressionError

try:
    result = safe_eval("__builtins__['exec']('print(1)')")
except UnsafeExpressionError as e:
    print(f"Unsafe expression detected: {e}")
```

### Encrypt to file

Encrypt the given Python code using multiple methods and embed it as comments in a Python file.

```python
Parameters:
        code (str): The Python code to encrypt.
        output_file (str): The path to the output Python file to embed encrypted code.
        mapping (dict): The mapping dictionary for character replacements.

Returns:
        None
```

### Run

Decrypt and execute the Python code embedded in the specified file or stream.

```python
Parameters:
        encrypted_source (str or stream): Path to the file or a file-like object with embedded encrypted code.
        mapping (dict): The mapping dictionary for character replacements.

Returns:
        None
```

### Decrypt to file

Decrypt the code embedded in the specified file/stream and write it to an output file/stream.

```python
Parameters:
        encrypted_file (str or stream): Path to the source or a file-like object.
        output_file (str or stream): Path to the destination or a file-like object.
        mapping (dict): The mapping dictionary for character replacements.

Returns:
        None
```

### Encrypt

Encrypt the code and return it.

```python
Parameters:
        code (str or bytes): The Python code to encrypt.
        mapping (dict): The mapping dictionary for character replacements.

Returns:
        str: The encrypted code.
```

### Decrypt

Decrypt the code and return it.

```python
Parameters:
        encrypted_code (str): The Python code to decrypt.
        mapping (dict): The mapping dictionary for character replacements.

Returns:
        str: The decrypted code.
```
