### Install Tomli using pip Source: https://github.com/hukkin/tomli/blob/master/README.md Use pip to install the Tomli library. This command installs the latest version from PyPI. ```bash pip install tomli ``` -------------------------------- ### Run Benchmark Against Latest Tomli PyPI Release Source: https://github.com/hukkin/tomli/blob/master/benchmark/README.md Execute the benchmark suite against the most recent version of Tomli published on PyPI. This command uses the 'benchmark-pypi' tox environment. ```bash tox -e benchmark-pypi ``` -------------------------------- ### Run Benchmark Against Local Tomli State Source: https://github.com/hukkin/tomli/blob/master/benchmark/README.md Execute the benchmark suite against the locally available Tomli code. This command uses the 'benchmark' tox environment. ```bash tox -e benchmark ``` -------------------------------- ### Initialize tomllib Tests Source: https://github.com/hukkin/tomli/blob/master/tomllib.md This code initializes the test suite for the `tomllib` module in Python's standard library. It uses `unittest` and `load_package_tests` for test discovery. ```python import unittest from . import load_tests unittest.main() ``` ```python import os from test.support import load_package_tests def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args) ``` -------------------------------- ### tomli.load - Parse TOML from a binary file Source: https://context7.com/hukkin/tomli/llms.txt The `load` function reads and parses TOML content from a binary file object. The file must be opened in binary mode (`"rb"`). ```APIDOC ## tomli.load - Parse TOML from a binary file ### Description Reads and parses TOML content from a binary file object. The file must be opened in binary mode (`"rb"`) to ensure proper UTF-8 decoding with universal newlines disabled, as required by the TOML specification. ### Method `tomli.load(f: BinaryIO, *, decoder: Optional[TomlDecoder] = None) -> dict` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **f** (BinaryIO) - Required - A file-like object opened in binary mode (`"rb"`). - **decoder** (Optional[TomlDecoder]) - Optional - A custom decoder instance. ### Request Example ```python import tomli from pathlib import Path config_content = """ [app] name = \"MyApp\"\nversion = \"1.0.0\" [app.settings] log_level = \"INFO\"\nmax_connections = 100 features = [\"auth\", \"logging\", \"cache\"] [[app.plugins]] name = \"auth-plugin\" enabled = true [[app.plugins]] name = \"cache-plugin\" enabled = false """ Path("config.toml").write_text(config_content) with open("config.toml", "rb") as f: config = tomli.load(f) print(config) Path("config.toml").unlink() ``` ### Response #### Success Response (200) - **dict** - A Python dictionary representing the parsed TOML content. #### Response Example ```json { "app": { "name": "MyApp", "version": "1.0.0", "settings": { "log_level": "INFO", "max_connections": 100, "features": [ "auth", "logging", "cache" ] }, "plugins": [ { "name": "auth-plugin", "enabled": true }, { "name": "cache-plugin", "enabled": false } ] } } ``` ``` -------------------------------- ### Tomli Benchmark Results Source: https://github.com/hukkin/tomli/blob/master/README.md Displays the performance comparison of tomli against other TOML parsers. The benchmark measures execution time and calculates performance relative to rtoml. ```console foo@bar:~/dev/tomli$ python benchmark/run.py Parsing data.toml 5000 times: ------------------------------------------------------ parser | exec time | performance (more is better) -----------+------------+----------------------------- rtoml | 0.323 s | baseline (100%) pytomlpp | 0.365 s | 88.40% tomli | 1.44 s | 22.36% toml | 3.03 s | 10.65% tomlkit | 20.6 s | 1.57% ``` -------------------------------- ### Tomli Performance Benchmark Results Source: https://github.com/hukkin/tomli/blob/master/README.md Console output showing the performance benchmark results for various Python TOML parsers, including tomli, rtoml, pytomlpp, toml, and tomlkit. The results are based on parsing a data file 5000 times. ```console foo@bar:~/dev/tomli$ python --version Python 3.14.2 foo@bar:~/dev/tomli$ pip freeze pytomlpp==1.1.0 rtoml==0.13.0 toml==0.10.2 tomli @ file:///home/foo/dev/tomli tomlkit==0.13.3 foo@bar:~/dev/tomli$ python benchmark/run.py Parsing data.toml 5000 times: ------------------------------------------------------ parser | exec time | performance (more is better) -----------+------------+----------------------------- rtoml | 0.328 s | baseline (100%) pytomlpp | 0.365 s | 89.75% tomli | 0.838 s | 39.12% toml | 3.01 s | 10.90% tomlkit | 20.7 s | 1.59% ``` -------------------------------- ### Parse a TOML file with tomli.load Source: https://github.com/hukkin/tomli/blob/master/README.md Load TOML data from a file using the `tomli.load` function. The file must be opened in binary mode (`"rb"`) to ensure correct UTF-8 decoding and universal newlines are disabled. ```python import tomli with open("path_to_file/conf.toml", "rb") as f: toml_dict = tomli.load(f) ``` -------------------------------- ### Parse TOML File with tomli.load Source: https://context7.com/hukkin/tomli/llms.txt Use `tomli.load` to parse TOML content from a binary file object opened in read-binary mode (`'rb'`). This ensures correct UTF-8 decoding and universal newlines as required by the TOML specification. ```python import tomli from pathlib import Path # Create a sample TOML file config_content = """ [app] name = "MyApp" version = "1.0.0" [app.settings] log_level = "INFO" max_connections = 100 features = ["auth", "logging", "cache"] [[app.plugins]] name = "auth-plugin" enabled = true [[app.plugins]] name = "cache-plugin" enabled = false """ # Write sample file Path("config.toml").write_text(config_content) # Parse TOML from file - must use binary mode "rb" with open("config.toml", "rb") as f: config = tomli.load(f) print(config["app"]["name"]) # "MyApp" print(config["app"]["version"]) # "1.0.0" print(config["app"]["settings"]["log_level"]) # "INFO" print(config["app"]["settings"]["features"]) # ["auth", "logging", "cache"] print(config["app"]["plugins"][0]["name"]) # "auth-plugin" print(config["app"]["plugins"][1]["enabled"]) # False # Clean up Path("config.toml").unlink() ``` -------------------------------- ### Parse a TOML string with tomli.loads Source: https://github.com/hukkin/tomli/blob/master/README.md Load TOML data directly from a string using the `tomli.loads` function. Ensure the TOML string is correctly formatted. ```python import tomli toml_str = """ [[players]] name = "Lehtinen" number = 26 [[players]] name = "Numminen" number = 27 """ toml_dict = tomli.loads(toml_str) assert toml_dict == { "players": [{"name": "Lehtinen", "number": 26}, {"name": "Numminen", "number": 27}] } ``` -------------------------------- ### TOML Type Mapping Reference Source: https://context7.com/hukkin/tomli/llms.txt Demonstrates the mapping of various TOML data types to their corresponding Python types, including strings, numbers, booleans, dates, times, arrays, tables, and inline tables. ```python import tomli from datetime import datetime, date, time, timezone import math toml_str = """ # Strings basic_string = "Hello, World!" literal_string = 'C:\\path\\to\\file' multiline = ''' Multiple lines ''' # Numbers integer = 42 negative = -17 hex_value = 0xDEADBEEF binary = 0b11010110 float_val = 3.14 scientific = 6.022e23 infinity = inf not_a_number = nan # Boolean enabled = true disabled = false # Date and Time date_only = 2024-01-15 datetime_utc = 2024-01-15T10:30:00Z datetime_offset = 2024-01-15T10:30:00-05:00 datetime_local = 2024-01-15T10:30:00 time_only = 14:30:00 # Collections array = [1, 2, 3, 4, 5] mixed_array = ["string", 42, true, 3.14] [table] key = "value" [inline] data = { name = "Alice", age = 30 } """ config = tomli.loads(toml_str) # String types -> str assert isinstance(config["basic_string"], str) assert config["basic_string"] == "Hello, World!" # Integer types -> int assert isinstance(config["integer"], int) assert config["hex_value"] == 0xDEADBEEF assert config["binary"] == 0b11010110 # Float types -> float assert isinstance(config["float_val"], float) assert config["scientific"] == 6.022e23 assert math.isinf(config["infinity"]) assert math.isnan(config["not_a_number"]) # Boolean types -> bool assert config["enabled"] is True assert config["disabled"] is False # Date types -> datetime.date assert isinstance(config["date_only"], date) assert config["date_only"] == date(2024, 1, 15) # Datetime with timezone -> datetime.datetime with tzinfo assert isinstance(config["datetime_utc"], datetime) assert config["datetime_utc"].tzinfo == timezone.utc # Local datetime -> datetime.datetime with tzinfo=None assert isinstance(config["datetime_local"], datetime) assert config["datetime_local"].tzinfo is None # Time only -> datetime.time assert isinstance(config["time_only"], time) assert config["time_only"] == time(14, 30, 0) # Arrays -> list assert isinstance(config["array"], list) assert config["array"] == [1, 2, 3, 4, 5] ``` -------------------------------- ### Verify Type Mappings in TOML Configuration Source: https://context7.com/hukkin/tomli/llms.txt Asserts that specific keys in the parsed TOML configuration are dictionaries. This is useful for validating the structure of loaded configuration data. ```python assert isinstance(config["table"], dict) assert isinstance(config["inline"]["data"], dict) print("All type mappings verified!") ``` -------------------------------- ### Conditional Import of TOML Parser Source: https://github.com/hukkin/tomli/blob/master/README.md This Python code snippet demonstrates how to import a TOML parser, prioritizing the standard library's `tomllib` for Python 3.11+ and falling back to `tomli` for older versions. It ensures seamless compatibility across different Python environments. ```python import sys if sys.version_info >= (3, 11): import tomllib else: import tomli as tomllib tomllib.loads("['This parses fine with Python 3.6+']") ``` -------------------------------- ### tomli.loads - Parse TOML from a string Source: https://context7.com/hukkin/tomli/llms.txt The `loads` function parses a TOML-formatted string and returns a Python dictionary. It handles all TOML data types and normalizes line endings. ```APIDOC ## tomli.loads - Parse TOML from a string ### Description Parses a TOML-formatted string and returns a Python dictionary. Handles all TOML data types including strings, integers, floats, booleans, dates, times, arrays, and tables. Automatically normalizes line endings by converting `\r\n` to `\n`. ### Method `tomli.loads(s: str, *, decoder: Optional[TomlDecoder] = None) -> dict` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **s** (str) - Required - The TOML-formatted string to parse. - **decoder** (Optional[TomlDecoder]) - Optional - A custom decoder instance. ### Request Example ```python import tomli toml_str = """ title = \"My Application\"\ndebug = true [server]\nhost = \"localhost\"\nport = 8080\ntimeout = 30.5 [database]\nconnection_string = \"postgresql://localhost/mydb\"\npool_size = 10 [[players]] name = \"Lehtinen\"\nnumber = 26 [[players]] name = \"Numminen\"\nnumber = 27 [dates]\ncreated = 2024-01-15\nupdated = 2024-01-15T10:30:00Z\n""" config = tomli.loads(toml_str) print(config) ``` ### Response #### Success Response (200) - **dict** - A Python dictionary representing the parsed TOML content. #### Response Example ```json { "title": "My Application", "debug": true, "server": { "host": "localhost", "port": 8080, "timeout": 30.5 }, "database": { "connection_string": "postgresql://localhost/mydb", "pool_size": 10 }, "players": [ { "name": "Lehtinen", "number": 26 }, { "name": "Numminen", "number": 27 } ], "dates": { "created": "2024-01-15", "updated": "2024-01-15T10:30:00Z" } } ``` ``` -------------------------------- ### TOML Parsing Compatibility Layer Source: https://context7.com/hukkin/tomli/llms.txt Implement a compatibility layer for TOML parsing that uses Python's built-in `tomllib` for versions 3.11+ and falls back to `tomli` for older versions. This allows consistent TOML parsing across different Python environments. ```python import sys # Compatibility import pattern if sys.version_info >= (3, 11): import tomllib else: import tomli as tomllib # Now use tomllib regardless of Python version toml_content = """ [project] name = "my-package" version = "1.0.0" dependencies = ["requests", "click"] [project.optional-dependencies] dev = ["pytest", "mypy"] """ config = tomllib.loads(toml_content) print(config["project"]["name"]) # "my-package" print(config["project"]["dependencies"]) # ["requests", "click"] ``` -------------------------------- ### Custom Float Parsing with Rounding Source: https://context7.com/hukkin/tomli/llms.txt Define a custom function to parse float strings, such as rounding to a specific number of decimal places, and pass it to `tomli.loads` via the `parse_float` parameter. ```python import tomli # Example 2: Using a custom parser function def custom_float_parser(float_str: str) -> float: """Custom parser that rounds to 2 decimal places.""" return round(float(float_str), 2) toml_str = """ value1 = 3.14159 value2 = 2.71828 """ config = tomli.loads(toml_str, parse_float=custom_float_parser) print(config["value1"]) # 3.14 print(config["value2"]) # 2.72 ``` -------------------------------- ### Parse TOML floats as decimal.Decimal Source: https://github.com/hukkin/tomli/blob/master/README.md Customize float parsing by providing a callable, such as `decimal.Decimal`, to the `parse_float` argument in `tomli.loads`. This is useful for avoiding float inaccuracies. ```python from decimal import Decimal import tomli toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal) assert isinstance(toml_dict["precision-matters"], Decimal) assert toml_dict["precision-matters"] == Decimal("0.982492") ``` -------------------------------- ### Update tomllib Parser Signatures Source: https://github.com/hukkin/tomli/blob/master/tomllib.md This code snippet shows modifications to the `_parser.py` file within the `tomllib` module. It involves renaming internal variables and adding the positional-only argument marker '/' to the `load` and `loads` function signatures. ```python In `cpython:Lib/tomllib/_parser.py` replace `__fp` with `fp` and `__s` with `s`. Add the `/` to `load` and `loads` function signatures. ``` -------------------------------- ### Handle invalid TOML with tomli.TOMLDecodeError Source: https://github.com/hukkin/tomli/blob/master/README.md Catch `tomli.TOMLDecodeError` when parsing invalid TOML content. Error messages are informational and may change between versions. ```python import tomli try: toml_dict = tomli.loads("]] this is invalid TOML [[") except tomli.TOMLDecodeError: print("Yep, definitely not valid.") ``` -------------------------------- ### Tomli Dependency Specifier for Older Python Source: https://github.com/hukkin/tomli/blob/master/README.md Use this dependency specifier in your project's configuration to conditionally require the `tomli` package only for Python versions older than 3.11. ```text tomli >= 1.1.0 ; python_version < "3.11" ``` -------------------------------- ### Handle TOMLDecodeError in Tomli Source: https://context7.com/hukkin/tomli/llms.txt Catch `tomli.TOMLDecodeError` to handle invalid TOML syntax. This exception, inheriting from `ValueError`, provides attributes like `msg`, `lineno`, `colno`, and `pos` for detailed error reporting. ```python import tomli # Example 1: Basic error handling invalid_toml = "]] this is invalid TOML [[" try: tomli.loads(invalid_toml) except tomli.TOMLDecodeError as e: print(f"Parse error: {e}") # Parse error: Invalid statement (at line 1, column 1) # Example 2: Accessing detailed error attributes invalid_toml = """ [server] host = "localhost" port = not_a_number """ try: tomli.loads(invalid_toml) except tomli.TOMLDecodeError as e: print(f"Error message: {e.msg}") # "Invalid value" print(f"Line number: {e.lineno}") # 4 print(f"Column number: {e.colno}") # 8 print(f"Position in doc: {e.pos}") # Position index # Example 3: Handling various TOML syntax errors test_cases = [ ('key = "unterminated string', "Unterminated string"), ("[table", "Missing closing bracket"), ("key = 2024-13-01", "Invalid date"), ('key = {"nested: "invalid"}', "Invalid inline table"), ] for invalid_content, description in test_cases: try: tomli.loads(invalid_content) except tomli.TOMLDecodeError as e: print(f"{description}: {e}") ``` -------------------------------- ### tomli.TOMLDecodeError - Handle invalid TOML Source: https://context7.com/hukkin/tomli/llms.txt The `TOMLDecodeError` exception is raised when parsing invalid TOML content. It extends `ValueError` and provides detailed error information. ```APIDOC ## tomli.TOMLDecodeError - Handle invalid TOML ### Description The `TOMLDecodeError` exception is raised when parsing invalid TOML content. It extends `ValueError` and provides detailed error information including the error message, the document being parsed, position, line number, and column number where the error occurred. ### Method `tomli.TOMLDecodeError(msg: str, doc: str, pos: int, lineno: int, colno: int)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import tomli # Example 1: Basic error handling invalid_toml = "]] this is invalid TOML [[" try: tomli.loads(invalid_toml) except tomli.TOMLDecodeError as e: print(f"Parse error: {e}") # Example 2: Accessing detailed error attributes invalid_toml = """ [server] host = \"localhost\" port = not_a_number """ try: tomli.loads(invalid_toml) except tomli.TOMLDecodeError as e: print(f"Error message: {e.msg}") print(f"Line number: {e.lineno}") print(f"Column number: {e.colno}") print(f"Position in doc: {e.pos}") # Example 3: Handling various TOML syntax errors test_cases = [ ('key = "unterminated string', "Unterminated string"), ("[table", "Missing closing bracket"), ("key = 2024-13-01", "Invalid date"), ('key = {"nested: \"invalid\"}"', "Invalid inline table"), ] for invalid_content, description in test_cases: try: tomli.loads(invalid_content) except tomli.TOMLDecodeError as e: print(f"{description}: {e}") ``` ### Response #### Success Response (200) None (This is an exception class) #### Response Example None ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.