Skip to content

Base

Base classes, mixins, and utilities for exporting data.

Each exporter should inherit from the BaseExporter class and implement the export method. The export method should return the exported content as an instance of the ExporterReturnType typed dictionary.

Bases: TypedDict

Exporter Return Type.

Attributes:

NameTypeDescription
contentOptional[str]

The exported content.

importsOptional[List[Tuple[str, ImportPosition]]]

The additional imports required for the exported content.

environment_variablesOptional[List[Tuple[str, str]]]

The environment variables to set.

before_exportOptional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

The exported content before the main export and its position.

after_exportOptional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

The exported content after the main export and its position.

Bases: ABC

Base exporter.

Parameters:

NameTypeDescriptionDefault
*argsAny

The positional arguments.

()
**kwargsAny

The keyword arguments.

{}
Source code in waldiez/exporting/base/base_exporter.py
@abc.abstractmethod
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Initialize the exporter.

    Parameters
    ----------
    *args : Any
        The positional arguments.
    **kwargs : Any
        The keyword arguments.
    """
    raise NotImplementedError("Method not implemented.")

export() -> ExporterReturnType abstractmethod

Export the content.

Returns:

TypeDescription
ExporterReturnType

The exported content.

Source code in waldiez/exporting/base/base_exporter.py
@abc.abstractmethod
def export(self) -> ExporterReturnType:
    """Export the content.

    Returns
    -------
    ExporterReturnType
        The exported content.
    """

generate() -> Optional[str]

Generate the main export.

Returns:

TypeDescription
str

The exported content.

Source code in waldiez/exporting/base/base_exporter.py
def generate(
    self,
) -> Optional[str]:
    """Generate the main export.

    Returns
    -------
    str
        The exported content.
    """

get_after_export() -> Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

Generate the content after the main export.

Returns:

TypeDescription
Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

The exported content after the main export and its position.

Source code in waldiez/exporting/base/base_exporter.py
def get_after_export(
    self,
) -> Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]:
    """Generate the content after the main export.

    Returns
    -------
    Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]
        The exported content after the main export and its position.
    """

get_before_export() -> Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

Generate the content before the main export.

Returns:

TypeDescription
Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]

The exported content before the main export and its position.

Source code in waldiez/exporting/base/base_exporter.py
def get_before_export(
    self,
) -> Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]:
    """Generate the content before the main export.

    Returns
    -------
    Optional[List[Tuple[str, Union[ExportPosition, AgentPosition]]]]
        The exported content before the main export and its position.
    """

get_environment_variables() -> Optional[List[Tuple[str, str]]]

Get the environment variables to set.

Returns:

TypeDescription
Optional[Set[Tuple[str, str]]]

The environment variables to set if any.

Source code in waldiez/exporting/base/base_exporter.py
def get_environment_variables(self) -> Optional[List[Tuple[str, str]]]:
    """Get the environment variables to set.

    Returns
    -------
    Optional[Set[Tuple[str, str]]]
        The environment variables to set if any.
    """

get_imports() -> Optional[List[Tuple[str, ImportPosition]]]

"Generate the imports string for the exporter.

Returns:

TypeDescription
Optional[Tuple[str, ImportPosition]]

The exported imports and the position of the imports.

Source code in waldiez/exporting/base/base_exporter.py
def get_imports(self) -> Optional[List[Tuple[str, ImportPosition]]]:
    """ "Generate the imports string for the exporter.

    Returns
    -------
    Optional[Tuple[str, ImportPosition]]
        The exported imports and the position of the imports.
    """

Export position enum.

ExportPosition(position: ExportPositions, order: int = 0) dataclass

Export position.

Optionally, the order can be provided to sort the exported content.

ExportPositions

Bases: Enum

Export position.

Attributes:

NameTypeDescription
TOPint

The top of the export (name, comments etc.)

IMPORTSint

The imports section.

MODELSint

The models section (define the llm_configs).

SKILLSint

The skills section (generate the skill files, and import them)

AGENTSint

The agents section.

CHATSint

The chats section (e.g. agent.initiate_chat, or initiate_chats)

BOTTOMint

The bottom part of the export (like the main function and calling it).

Import position enum.

ImportPosition

Bases: Enum

Import position.

Attributes:

NameTypeDescription
BUILTINSint

The top of the import (builtins)

THIRD_PARTYint

The third party imports.

LOCALint

The local imports.

Agent position generation.

AgentPosition(agent: Optional[WaldiezAgent], position: AgentPositions, order: int = 0) dataclass

Agent position.

Attributes:

NameTypeDescription
agentOptional[WaldiezAgent]

The agent.

positionAgentPositions

The position.

orderint

The order of the agent position.

Raises:

TypeDescription
ValueError

If the position is not "BEFORE_ALL" or "AFTER_ALL" and the agent is not provided.

AgentPositions

Bases: Enum

Agent positions.

Attributes:

NameTypeDescription
BEFORE_ALLint

Before all agents.

BEFOREint

Before the agent.

AS_ARGUMENTint

As an argument of the agent's initialization.

AFTERint

After the agent.

AFTER_ALLint

After all agents.

The base exporter mixin.

ExporterMixin

Static methods to be used by the exporters.

comment(for_notebook: bool, hashtags: int = 1) -> str staticmethod

Comment the text.

Parameters:

NameTypeDescriptionDefault
for_notebookbool

Whether the comment is for a notebook or not.

required
hashtagsint

The number of hashtags (for notebooks), by default 1.

1

Returns:

TypeDescription
str

The commented text.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def comment(for_notebook: bool, hashtags: int = 1) -> str:
    """Comment the text.

    Parameters
    ----------
    for_notebook : bool
        Whether the comment is for a notebook or not.
    hashtags : int, optional
        The number of hashtags (for notebooks), by default 1.

    Returns
    -------
    str
        The commented text.
    """
    return comment(for_notebook=for_notebook, hashtags=hashtags)

get_comment(key: CommentKey, for_notebook: bool) -> str staticmethod

Get the comment string.

Parameters:

NameTypeDescriptionDefault
keyCommentKey

The comment key.

required
for_notebookbool

Whether the comment is for a notebook or not.

required

Returns:

TypeDescription
str

The comment string.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def get_comment(key: CommentKey, for_notebook: bool) -> str:
    """Get the comment string.

    Parameters
    ----------
    key : CommentKey
        The comment key.
    for_notebook : bool
        Whether the comment is for a notebook or not.
    Returns
    -------
    str
        The comment string.
    """
    return get_comment(key=key, for_notebook=for_notebook)

get_valid_instance_name(instance: Tuple[str, str], current_names: Dict[str, str], prefix: str = 'w', max_length: int = 64) -> Dict[str, str] staticmethod

Get a valid instance name.

Parameters:

NameTypeDescriptionDefault
instanceTuple[str, str]

The instance id and possible name.

required
current_namesDict[str, str]

The current names.

required
prefixstr

The prefix for the instance name, by default "w".

'w'
max_lengthint

The maximum length of the variable name, by default 64

64

Returns:

TypeDescription
Dict[str, str]

The updated dictionary of current names.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def get_valid_instance_name(
    instance: Tuple[str, str],
    current_names: Dict[str, str],
    prefix: str = "w",
    max_length: int = 64,
) -> Dict[str, str]:
    """Get a valid instance name.

    Parameters
    ----------
    instance : Tuple[str, str]
        The instance id and possible name.
    current_names : Dict[str, str]
        The current names.
    prefix : str, optional
        The prefix for the instance name, by default "w".
    max_length : int, optional
        The maximum length of the variable name, by default 64
    Returns
    -------
    Dict[str, str]
        The updated dictionary of current names.
    """
    return get_valid_instance_name(
        instance=instance,
        current_names=current_names,
        prefix=prefix,
        max_length=max_length,
    )

path_resolver(path: str) -> str staticmethod

Get the path string.

Parameters:

NameTypeDescriptionDefault
pathstr

The path.

required

Returns:

TypeDescription
str

The path string.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def path_resolver(path: str) -> str:
    """Get the path string.

    Parameters
    ----------
    path : str
        The path.

    Returns
    -------
    str
        The path string.
    """
    return get_path_string(path)

serializer(item: Any, tabs: int = 1) -> str staticmethod

Get the string representation of an item.

Parameters:

NameTypeDescriptionDefault
itemAny

The item.

required
tabsint

The number of tabs for indentation, by default 1.

1

Returns:

TypeDescription
str

The string representation of the item.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def serializer(item: Any, tabs: int = 1) -> str:
    """Get the string representation of an item.

    Parameters
    ----------
    item : Any
        The item.
    tabs : int, optional
        The number of tabs for indentation, by default 1.
    Returns
    -------
    str
        The string representation of the item.
    """
    return get_item_string(item=item, tabs=tabs)

string_escape(string: str) -> str staticmethod

Get a string with escaped quotes and newlines.

Parameters:

NameTypeDescriptionDefault
stringstr

The original string.

required

Returns:

TypeDescription
str

The escaped string.

Source code in waldiez/exporting/base/mixin.py
@staticmethod
def string_escape(string: str) -> str:
    """Get a string with escaped quotes and newlines.

    Parameters
    ----------
    string : str
        The original string.

    Returns
    -------
    str
        The escaped string.
    """
    return get_escaped_string(string)

Generic utils to be used for exporting.

CommentKey = Literal['agents', 'imports', 'skills', 'models', 'nested', 'run', 'logging'] module-attribute

Possible keys for comments.

comment(for_notebook: bool, hashtags: int = 1) -> str

Get the comment string.

Parameters:

NameTypeDescriptionDefault
for_notebookbool

Whether the comment is for a notebook or not.

required
hashtagsint

The number of hashtags (for notebooks), by default 1.

1

Returns:

TypeDescription
str

The comment string.

Example
>>> comment(True, 2)
'## '
>>> comment(False)
'# '
Source code in waldiez/exporting/base/utils/comments.py
def comment(for_notebook: bool, hashtags: int = 1) -> str:
    """Get the comment string.

    Parameters
    ----------
    for_notebook : bool
        Whether the comment is for a notebook or not.
    hashtags : int, optional
        The number of hashtags (for notebooks), by default 1.

    Returns
    -------
    str
        The comment string.
    Example
    -------
    ```python
    >>> comment(True, 2)
    '## '
    >>> comment(False)
    '# '
    ```
    """
    content = "# "
    if for_notebook:
        content += "#" * hashtags + " "
    return content

comments

Utilities for comments.

comment Get a comment string. get_comment Get a comment string for some common keys (notebook headings).

CommentKey = Literal['agents', 'imports', 'skills', 'models', 'nested', 'run', 'logging'] module-attribute

Possible keys for comments.

comment(for_notebook: bool, hashtags: int = 1) -> str

Get the comment string.

Parameters:

NameTypeDescriptionDefault
for_notebookbool

Whether the comment is for a notebook or not.

required
hashtagsint

The number of hashtags (for notebooks), by default 1.

1

Returns:

TypeDescription
str

The comment string.

Example
>>> comment(True, 2)
'## '
>>> comment(False)
'# '
Source code in waldiez/exporting/base/utils/comments.py
def comment(for_notebook: bool, hashtags: int = 1) -> str:
    """Get the comment string.

    Parameters
    ----------
    for_notebook : bool
        Whether the comment is for a notebook or not.
    hashtags : int, optional
        The number of hashtags (for notebooks), by default 1.

    Returns
    -------
    str
        The comment string.
    Example
    -------
    ```python
    >>> comment(True, 2)
    '## '
    >>> comment(False)
    '# '
    ```
    """
    content = "# "
    if for_notebook:
        content += "#" * hashtags + " "
    return content

get_comment(key: CommentKey, for_notebook: bool) -> str

Get a comment string for some common keys.

The key is a heading (in a notebook) or just a comment (in a script).

Parameters:

NameTypeDescriptionDefault
keyagents | imports | skills | models | nested | run | logging

The key.

required
for_notebookbool

Whether the comment is for a notebook.

required

Returns:

TypeDescription
str

The comment string.

Example
>>> get_comment("agents", True)

'## Agents'
>>> get_comment("skills", False)

'# Skills'
Source code in waldiez/exporting/base/utils/comments.py
def get_comment(
    key: CommentKey,
    for_notebook: bool,
) -> str:
    """Get a comment string for some common keys.

    The key is a heading (in a notebook) or just a comment (in a script).

    Parameters
    ----------
    key : "agents"|"imports"|"skills"|"models"|"nested"|"run"|"logging"
        The key.
    for_notebook : bool
        Whether the comment is for a notebook.

    Returns
    -------
    str
        The comment string.

    Example
    -------
    ```python
    >>> get_comment("agents", True)

    '## Agents'
    >>> get_comment("skills", False)

    '# Skills'
    ```
    """
    # pylint: disable=too-many-return-statements
    if key == "agents":
        return "\n" + comment(for_notebook, 2) + "Agents\n"
    if key == "imports":
        return "\n" + comment(for_notebook, 2) + "Imports\n"
    if key == "skills":
        return "\n" + comment(for_notebook, 2) + "Skills\n"
    if key == "models":
        return "\n" + comment(for_notebook, 2) + "Models\n"
    if key == "nested":
        return "\n" + comment(for_notebook, 2) + "Nested Chats\n"
    if key == "run":
        return "\n" + comment(for_notebook, 2) + "Run the flow\n"
    if key == "logging":
        return "\n" + comment(for_notebook, 2) + "Start Logging\n"
    return comment(for_notebook)

get_comment(key: CommentKey, for_notebook: bool) -> str

Get a comment string for some common keys.

The key is a heading (in a notebook) or just a comment (in a script).

Parameters:

NameTypeDescriptionDefault
keyagents | imports | skills | models | nested | run | logging

The key.

required
for_notebookbool

Whether the comment is for a notebook.

required

Returns:

TypeDescription
str

The comment string.

Example
>>> get_comment("agents", True)

'## Agents'
>>> get_comment("skills", False)

'# Skills'
Source code in waldiez/exporting/base/utils/comments.py
def get_comment(
    key: CommentKey,
    for_notebook: bool,
) -> str:
    """Get a comment string for some common keys.

    The key is a heading (in a notebook) or just a comment (in a script).

    Parameters
    ----------
    key : "agents"|"imports"|"skills"|"models"|"nested"|"run"|"logging"
        The key.
    for_notebook : bool
        Whether the comment is for a notebook.

    Returns
    -------
    str
        The comment string.

    Example
    -------
    ```python
    >>> get_comment("agents", True)

    '## Agents'
    >>> get_comment("skills", False)

    '# Skills'
    ```
    """
    # pylint: disable=too-many-return-statements
    if key == "agents":
        return "\n" + comment(for_notebook, 2) + "Agents\n"
    if key == "imports":
        return "\n" + comment(for_notebook, 2) + "Imports\n"
    if key == "skills":
        return "\n" + comment(for_notebook, 2) + "Skills\n"
    if key == "models":
        return "\n" + comment(for_notebook, 2) + "Models\n"
    if key == "nested":
        return "\n" + comment(for_notebook, 2) + "Nested Chats\n"
    if key == "run":
        return "\n" + comment(for_notebook, 2) + "Run the flow\n"
    if key == "logging":
        return "\n" + comment(for_notebook, 2) + "Start Logging\n"
    return comment(for_notebook)

get_escaped_string(string: str) -> str

Get a string with escaped quotes and newlines.

Parameters:

NameTypeDescriptionDefault
stringstr

The original string.

required

Returns:

TypeDescription
str

The escaped string.

Source code in waldiez/exporting/base/utils/naming.py
def get_escaped_string(string: str) -> str:
    """Get a string with escaped quotes and newlines.

    Parameters
    ----------
    string : str
        The original string.

    Returns
    -------
    str
        The escaped string.
    """
    return string.replace('"', '\\"').replace("\n", "\\n")

get_item_string(item: Any, tabs: int = 1) -> str

Convert an item to a formatted string with given indentation.

Parameters:

NameTypeDescriptionDefault
itemAny

The item to convert.

required
tabsint

The number of tabs, by default 1.

1

Returns:

TypeDescription
str

The formatted string.

Example
>>> obj = {"a": 1, "b": [1, 2, 3]}
>>> get_item_string(obj)
{
    "a": 1,
    "b": [
        1,
        2,
        3
    ]
}
>>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
>>> get_item_string(obj, 2)
{
        "a": 1,
        "b": [
            1,
            2,
            3
        ],
        "c": {
            "d": 4
        }
}
Source code in waldiez/exporting/base/utils/to_string.py
def get_item_string(item: Any, tabs: int = 1) -> str:
    """Convert an item to a formatted string with given indentation.

    Parameters
    ----------
    item : Any
        The item to convert.
    tabs : int, optional
        The number of tabs, by default 1.

    Returns
    -------
    str
        The formatted string.

    Example
    -------
    ```python
    >>> obj = {"a": 1, "b": [1, 2, 3]}
    >>> get_item_string(obj)
    {
        "a": 1,
        "b": [
            1,
            2,
            3
        ]
    }
    >>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
    >>> get_item_string(obj, 2)
    {
            "a": 1,
            "b": [
                1,
                2,
                3
            ],
            "c": {
                "d": 4
            }
    }
    ```
    """
    indent = " " * 4 * tabs  # Number of spaces corresponding to the tabs
    next_indent = (
        " " * 4 * (tabs + 1)
    )  # Number of spaces corresponding to the next tab level
    if isinstance(item, dict):
        items = []
        for key, value in item.items():
            items.append(
                f'{next_indent}"{key}": {get_item_string(value, tabs + 1)}'
            )
        # python3.10? f-string expression part cannot include a backslash
        items_string = ",\n".join(items)
        to_return = "\n" + items_string + "\n" + indent
        return f"{{{to_return}}}"
    if isinstance(item, list):
        items = []
        for sub_item in item:
            items.append(f"{next_indent}{get_item_string(sub_item, tabs + 1)}")
        # python3.10? f-string expression part cannot include a backslash
        items_string = ",\n".join(items)
        to_return = "\n" + items_string + "\n" + indent
        return f"[{to_return}]"

    if isinstance(item, str):
        if item.startswith("r'") or item.startswith('r"'):
            return item
        return f'"{item}"'

    if item is None:
        return "None"
    return str(item)

get_path_string(path: str) -> str

Get the path string.

Parameters:

NameTypeDescriptionDefault
pathstr

The string to check.

required

Returns:

TypeDescription
str

The local path string.

Source code in waldiez/exporting/base/utils/path_check.py
def get_path_string(path: str) -> str:
    """Get the path string.

    Parameters
    ----------
    path : str
        The string to check.

    Returns
    -------
    str
        The local path string.
    """
    resolved = _check_local_path(path)
    if not resolved:
        return _get_raw_path_string(path)
    return _get_raw_path_string(resolved)

get_valid_instance_name(instance: Tuple[str, str], current_names: Dict[str, str], prefix: str = 'w', max_length: int = MAX_VARIABLE_LENGTH) -> Dict[str, str]

Get a valid instance name.

If the instance id is already in the current names nothing is done. If the name already exists in the current names, the name is updated (with an index suffix).

Parameters:

NameTypeDescriptionDefault
instanceTuple[str, str]

The instance id and possible name.

required
current_namesDict[str, str]

The current names.

required
prefixstr

The prefix to use if the name starts with a digit, if the name is already in the current names, or if the name is already in the current names with an index suffix.

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
Dict[str, str]

The updated names.

Source code in waldiez/exporting/base/utils/naming.py
def get_valid_instance_name(
    instance: Tuple[str, str],
    current_names: Dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> Dict[str, str]:
    """Get a valid instance name.

    If the instance id is already in the current names nothing is done.
    If the name already exists in the current names,
        the name is updated (with an index suffix).

    Parameters
    ----------
    instance : Tuple[str, str]
        The instance id and possible name.
    current_names : Dict[str, str]
        The current names.
    prefix : str, optional
        The prefix to use if the name starts with a digit,
        if the name is already in the current names,
        or if the name is already in the current names with an index suffix.
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    Dict[str, str]
        The updated names.
    """
    instance_id, possible_name = instance[0], instance[1][:max_length]
    if instance_id in current_names:
        # already in the current names (it's id)
        return current_names
    new_names = current_names.copy()
    name = get_valid_python_variable_name(
        possible_name, prefix=prefix, max_length=max_length
    )
    if name in current_names.values():
        name = f"{prefix}_{name}"
    if name in current_names.values():
        index = 1
        while f"{name}_{index}" in current_names.values():
            index += 1
        name = f"{name}_{index}"
    new_names[instance_id] = name
    return new_names

naming

Utilities for naming.

Functions:

NameDescription
get_valid_python_variable_name

Make sure a string is a valid Python variable name.

get_valid_instance_name

Get a valid instance name.

get_escaped_string

Get a string with escaped quotes and newlines.

get_escaped_string(string: str) -> str

Get a string with escaped quotes and newlines.

Parameters:

NameTypeDescriptionDefault
stringstr

The original string.

required

Returns:

TypeDescription
str

The escaped string.

Source code in waldiez/exporting/base/utils/naming.py
def get_escaped_string(string: str) -> str:
    """Get a string with escaped quotes and newlines.

    Parameters
    ----------
    string : str
        The original string.

    Returns
    -------
    str
        The escaped string.
    """
    return string.replace('"', '\\"').replace("\n", "\\n")

get_valid_instance_name(instance: Tuple[str, str], current_names: Dict[str, str], prefix: str = 'w', max_length: int = MAX_VARIABLE_LENGTH) -> Dict[str, str]

Get a valid instance name.

If the instance id is already in the current names nothing is done. If the name already exists in the current names, the name is updated (with an index suffix).

Parameters:

NameTypeDescriptionDefault
instanceTuple[str, str]

The instance id and possible name.

required
current_namesDict[str, str]

The current names.

required
prefixstr

The prefix to use if the name starts with a digit, if the name is already in the current names, or if the name is already in the current names with an index suffix.

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
Dict[str, str]

The updated names.

Source code in waldiez/exporting/base/utils/naming.py
def get_valid_instance_name(
    instance: Tuple[str, str],
    current_names: Dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> Dict[str, str]:
    """Get a valid instance name.

    If the instance id is already in the current names nothing is done.
    If the name already exists in the current names,
        the name is updated (with an index suffix).

    Parameters
    ----------
    instance : Tuple[str, str]
        The instance id and possible name.
    current_names : Dict[str, str]
        The current names.
    prefix : str, optional
        The prefix to use if the name starts with a digit,
        if the name is already in the current names,
        or if the name is already in the current names with an index suffix.
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    Dict[str, str]
        The updated names.
    """
    instance_id, possible_name = instance[0], instance[1][:max_length]
    if instance_id in current_names:
        # already in the current names (it's id)
        return current_names
    new_names = current_names.copy()
    name = get_valid_python_variable_name(
        possible_name, prefix=prefix, max_length=max_length
    )
    if name in current_names.values():
        name = f"{prefix}_{name}"
    if name in current_names.values():
        index = 1
        while f"{name}_{index}" in current_names.values():
            index += 1
        name = f"{name}_{index}"
    new_names[instance_id] = name
    return new_names

get_valid_python_variable_name(possible: str, prefix: str = 'w', max_length: int = MAX_VARIABLE_LENGTH) -> str

Get a valid Python variable name from a possible name.

Parameters:

NameTypeDescriptionDefault
possiblestr

The possible name.

required
prefixstr

The prefix to use if the name starts with a digit or special character

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
str

The valid Python variable name.

Source code in waldiez/exporting/base/utils/naming.py
def get_valid_python_variable_name(
    possible: str,
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> str:
    """Get a valid Python variable name from a possible name.

    Parameters
    ----------
    possible : str
        The possible name.

    prefix : str, optional
        The prefix to use if the name starts with a digit or special character

    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    str
        The valid Python variable name.
    """

    def replacement(match: re.Match[str]) -> str:
        """Get the replacement for the match.

        Parameters
        ----------
        match : re.Match[str]
            The match.

        Returns
        -------
        str
            The replacement
        """
        if match.group(0) in ["->", "=>"]:
            return "to"
        if match.group(0) in ["<-", "<="]:
            return "from"
        if re.match(r"\W|^(?=\d)", match.group(0)):
            return "_"
        return match.group(0)

    possible = re.sub(r"->|=>|<-|<=|\W|^(?=\d)", replacement, possible)[
        :max_length
    ].lower()

    if not possible:
        return prefix + "_"
    if possible.startswith("_"):
        return f"{prefix}{possible}"
    if possible[0].isdigit():
        return f"{prefix}_{possible}"
    return possible

path_check

Path check utility functions.

get_path_string(path: str) -> str

Get the path string.

Parameters:

NameTypeDescriptionDefault
pathstr

The string to check.

required

Returns:

TypeDescription
str

The local path string.

Source code in waldiez/exporting/base/utils/path_check.py
def get_path_string(path: str) -> str:
    """Get the path string.

    Parameters
    ----------
    path : str
        The string to check.

    Returns
    -------
    str
        The local path string.
    """
    resolved = _check_local_path(path)
    if not resolved:
        return _get_raw_path_string(path)
    return _get_raw_path_string(resolved)

to_string

Utilities for converting items to strings.

To be used with dicts and/or lists.

get_item_string(item: Any, tabs: int = 1) -> str

Convert an item to a formatted string with given indentation.

Parameters:

NameTypeDescriptionDefault
itemAny

The item to convert.

required
tabsint

The number of tabs, by default 1.

1

Returns:

TypeDescription
str

The formatted string.

Example
>>> obj = {"a": 1, "b": [1, 2, 3]}
>>> get_item_string(obj)
{
    "a": 1,
    "b": [
        1,
        2,
        3
    ]
}
>>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
>>> get_item_string(obj, 2)
{
        "a": 1,
        "b": [
            1,
            2,
            3
        ],
        "c": {
            "d": 4
        }
}
Source code in waldiez/exporting/base/utils/to_string.py
def get_item_string(item: Any, tabs: int = 1) -> str:
    """Convert an item to a formatted string with given indentation.

    Parameters
    ----------
    item : Any
        The item to convert.
    tabs : int, optional
        The number of tabs, by default 1.

    Returns
    -------
    str
        The formatted string.

    Example
    -------
    ```python
    >>> obj = {"a": 1, "b": [1, 2, 3]}
    >>> get_item_string(obj)
    {
        "a": 1,
        "b": [
            1,
            2,
            3
        ]
    }
    >>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
    >>> get_item_string(obj, 2)
    {
            "a": 1,
            "b": [
                1,
                2,
                3
            ],
            "c": {
                "d": 4
            }
    }
    ```
    """
    indent = " " * 4 * tabs  # Number of spaces corresponding to the tabs
    next_indent = (
        " " * 4 * (tabs + 1)
    )  # Number of spaces corresponding to the next tab level
    if isinstance(item, dict):
        items = []
        for key, value in item.items():
            items.append(
                f'{next_indent}"{key}": {get_item_string(value, tabs + 1)}'
            )
        # python3.10? f-string expression part cannot include a backslash
        items_string = ",\n".join(items)
        to_return = "\n" + items_string + "\n" + indent
        return f"{{{to_return}}}"
    if isinstance(item, list):
        items = []
        for sub_item in item:
            items.append(f"{next_indent}{get_item_string(sub_item, tabs + 1)}")
        # python3.10? f-string expression part cannot include a backslash
        items_string = ",\n".join(items)
        to_return = "\n" + items_string + "\n" + indent
        return f"[{to_return}]"

    if isinstance(item, str):
        if item.startswith("r'") or item.startswith('r"'):
            return item
        return f'"{item}"'

    if item is None:
        return "None"
    return str(item)