Utilities

Decorators

edsl.utilities.decorators.add_edsl_version(func)[source]

Decorator for EDSL objects’ to_dict method. - Adds the EDSL version and class name to the dictionary.

edsl.utilities.decorators.jupyter_nb_handler(func)[source]

Decorator to run an async function in the event loop if it’s running, or synchronously otherwise.

edsl.utilities.decorators.remove_edsl_version(func)[source]

Decorator for the EDSL objects’ from_dict method. - Removes the EDSL version and class name from the dictionary. - Ensures backwards compatibility with older versions of EDSL.

edsl.utilities.decorators.sync_wrapper(async_func)[source]

Decorator to create a synchronous wrapper for an asynchronous function.

Interface

A module for displaying data in various formats.

edsl.utilities.interface.create_image(console, image_filename)[source]

Create an image from the console output.

edsl.utilities.interface.create_latex_table_from_data(data, filename=None, split_at_dot=True)[source]

This function takes a list of dictionaries and returns a LaTeX table as a string. The table can either be printed or written to a file.

>>> data = [{"a": [1, 2, 3], "b": [4, 5, 6]}]
>>> print(create_latex_table_from_data(data))
\begin{tabular}{|c|c|}
\hline
a & b \\
\hline
1 & 4 \\
2 & 5 \\
3 & 6 \\
\hline
\end{tabular}
edsl.utilities.interface.display_table(console, table, filename)[source]

Display the table using the rich library and save it to a file if a filename is provided.

edsl.utilities.interface.gen_html_sandwich(html_inner, interactive=False)[source]

Wrap the inner HTML content in a header and footer to make a complete HTML document.

edsl.utilities.interface.get_multiline_textsize(text, font)[source]

Get the size of the text when it is drawn on an image.

edsl.utilities.interface.human_readable_labeler_creator()[source]

Create a function that maps thread ids to human-readable labels.

It is structured as a closure, so that the mapping is persistent. I.e., when the returned function is called, it will use the same dictionary to map thread ids to human-readable labels if it’s seen that ID before; otherwise, it will add a new entry to the dictionary. This will persist across calls to the function.

edsl.utilities.interface.print_dataset_with_rich(data, filename=None, split_at_dot=True)[source]

Initialize console object.

edsl.utilities.interface.print_dict_as_html_table(d, show=False, key_name='Key', value_name='Value', filename=None)[source]

Print a dictionary as an HTML table.

Parameters:
  • d – The dictionary to print.

  • show – Whether to display the HTML table in the browser.

  • key_name – The name of the key column.

  • value_name – The name of the value column.

  • filename – The name of the file to save the HTML table to.

edsl.utilities.interface.print_dict_with_rich(d, key_name='Key', value_name='Value', filename=None)[source]

Print a dictionary as a table using the rich library.

Example: >>> print_dict_with_rich({“a”: 1, “b”: 2, “c”: 3}) ┏━━━━━┳━━━━━━━┓ ┃ Key ┃ Value ┃ ┡━━━━━╇━━━━━━━┩ │ a │ 1 │ │ b │ 2 │ │ c │ 3 │ └─────┴───────┘

edsl.utilities.interface.print_list_of_dicts_as_html_table(data, interactive=True)[source]

Print a list of dictionaries as an HTML table.

Parameters:
  • data – The list of dictionaries to print.

  • filename – The name of the file to save the HTML table to.

  • interactive – Whether to make the table interactive using DataTables.

edsl.utilities.interface.print_list_of_dicts_as_markdown_table(data, filename=None)[source]

Print a list of dictionaries as a Markdown table.

Parameters:
  • data – The list of dictionaries to print.

  • filename – The name of the file to save the Markdown table to.

edsl.utilities.interface.print_list_of_dicts_with_rich(data, filename=None, split_at_dot=True)[source]
edsl.utilities.interface.print_public_methods_with_doc(obj)[source]

Print the public methods of an object along with their docstrings.

edsl.utilities.interface.print_results_long(results, max_rows=None)[source]
edsl.utilities.interface.print_scenario_list(data)[source]
edsl.utilities.interface.print_table_with_rich(data, filename=None)[source]

Print a list of dictionaries as a table using the rich library.

Example: >>> data = [{“a”: 1, “b”: 2, “c”: 3}] >>> print_table_with_rich(data) ┏━━━┳━━━┳━━━┓ ┃ a ┃ b ┃ c ┃ ┡━━━╇━━━╇━━━┩ │ 1 │ 2 │ 3 │ └───┴───┴───┘ >>> data = [{“a”: 1, “b”: 2, “c”: 3},{“a”: 2, “b”: 9, “c”: 8}] >>> print_table_with_rich(data) ┏━━━┳━━━┳━━━┓ ┃ a ┃ b ┃ c ┃ ┡━━━╇━━━╇━━━┩ │ 1 │ 2 │ 3 │ │ 2 │ 9 │ 8 │ └───┴───┴───┘

edsl.utilities.interface.print_tally_with_rich(data, filename=None)[source]

Print a tally of values in a list using the rich library.

Example: >>> data = {‘a’:12, ‘b’:14, ‘c’:9} >>> print_tally_with_rich(data) ┏━━━━━━━┳━━━━━━━┓ ┃ Value ┃ Count ┃ ┡━━━━━━━╇━━━━━━━┩ │ a │ 12 │ │ b │ 14 │ │ c │ 9 │ └───────┴───────┘

edsl.utilities.interface.view_html(html)[source]

Display HTML content in a web browser.

Pastebin

Utilities

Utility functions for working with strings, dictionaries, and files.

class edsl.utilities.utilities.CustomEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
class edsl.utilities.utilities.HTMLSnippet(value)[source]

Bases: str

Create an object with html content (value).

view method allows you to view the html content in a web browser.

view()[source]

View the HTML content in a web browser.

edsl.utilities.utilities.clean_json(bad_json_str)[source]

Clean JSON string by replacing single quotes with double quotes

edsl.utilities.utilities.create_valid_var_name(s, transform_func: ~typing.Callable = <function <lambda>>) str[source]

Create a valid variable name from a string.

edsl.utilities.utilities.dict_hash(data: dict)[source]
edsl.utilities.utilities.dict_to_html(d)[source]

Convert a dictionary to an HTML table.

edsl.utilities.utilities.extract_json_from_string(s)[source]

Extract a JSON string from a string.

edsl.utilities.utilities.file_notice(file_name)[source]

Print a notice about the file being created.

edsl.utilities.utilities.fix_partial_correct_response(text: str) dict[source]
edsl.utilities.utilities.hash_value(value: str | int) str[source]

Hash a string or integer value using SHA-256.

edsl.utilities.utilities.is_gzipped(file_path)[source]

Check if a file is gzipped.

edsl.utilities.utilities.is_notebook() bool[source]

Check if the code is running in a Jupyter notebook or Google Colab.

edsl.utilities.utilities.is_valid_variable_name(name, allow_name=True)[source]

Check if a string is a valid variable name.

edsl.utilities.utilities.merge_dicts(dict_list)[source]

Merge a list of dictionaries into a single dictionary.

edsl.utilities.utilities.random_string() str[source]

Generate a random string of fixed length.

edsl.utilities.utilities.repair_json(json_string: str) str[source]

Attempt to repair a JSON string that is not valid JSON.

edsl.utilities.utilities.shorten_string(s, max_length, placeholder='...')[source]

Shorten a string to a maximum length by removing characters from the middle.

edsl.utilities.utilities.shortname_proposal(question, max_length=None)[source]

Take a question text and generate a slug.

edsl.utilities.utilities.text_to_shortname(long_text, forbidden_names=[])[source]

Create a slug for the question.

edsl.utilities.utilities.time_all_functions(module_or_class)[source]
edsl.utilities.utilities.time_it(func)[source]
edsl.utilities.utilities.valid_json(json_string)[source]

Check if a string is valid JSON.

edsl.utilities.utilities.write_api_key_to_env(api_key: str) str[source]

Write the user’s Expected Parrot key to their .env file.

If a .env file doesn’t exist in the current directory, one will be created.

Returns a string representing the absolute path to the .env file.