Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Python tomllib

    Python Programming Tutorials


    Python tomllib reads configuration data written in TOML. It is part of the standard library in Python 3.11 and later, so you do not need to install a package for reading TOML 1.0 files.

    TOML keeps common configuration files readable while still supporting structured values such as tables, arrays, dates, times, integers, and floating-point numbers. Python converts the parsed document into normal dictionaries and value types.

    Note: tomllib reads TOML but does not write it. Use a TOML-writing library when your application must update a file.

    Create a TOML Configuration File

    Save the following content as app.toml. Dotted sections become nested dictionaries, and the date becomes a Python date object.

    Example:

    title = "Order Service"
    debug = false
    launch_date = 2026-09-01
    ports = [8000, 8001]
    
    [database]
    host = "localhost"
    name = "orders"
    timeout = 2.5

    Read a TOML File

    Open the file in binary mode and pass the file object to tomllib.load(). Binary mode allows the parser to handle the required UTF-8 encoding consistently.

    Example:

    import tomllib
    
    # Open TOML files in binary mode for tomllib.load().
    with open("app.toml", "rb") as file:
        config = tomllib.load(file)
    
    print(config["title"])
    print(config["database"]["host"])
    print(config["ports"][0])
    print(type(config["launch_date"]))

    The function returns a dictionary. Access nested TOML tables with nested dictionary keys, and treat missing settings explicitly instead of assuming every file contains the same fields.

    Read Optional Settings Safely

    Use dict.get() for a setting that has a valid default. Use direct indexing for required settings so a missing key fails clearly during startup.

    Example:

    import tomllib
    
    with open("app.toml", "rb") as file:
        config = tomllib.load(file)
    
    # debug is optional, but the database name is required.
    debug_mode = config.get("debug", False)
    database_name = config["database"]["name"]
    
    print(f"Database: {database_name}")
    print(f"Debug enabled: {debug_mode}")

    Parse TOML from a String

    Use tomllib.loads() when the TOML document is already a string. Unlike load(), this function does not require a binary file object.

    Example:

    import tomllib
    
    source = """
    [user]
    name = "Aarav"
    roles = ["editor", "reviewer"]
    """
    
    # loads() parses a Python string.
    data = tomllib.loads(source)
    print(data["user"]["roles"])

    TOML and Python Types

    TOML value Python type
    String str
    Integer int
    Float float
    Boolean bool
    Array list
    Table dict
    Date and time date, time, or datetime

    Parse Decimal Values Precisely

    The optional parse_float argument changes how TOML floating-point values are created. For financial configuration, you can use Decimal to avoid ordinary binary floating-point rounding.

    Example:

    from decimal import Decimal
    import tomllib
    
    source = "tax_rate = 0.18"
    
    # Convert every TOML float directly to Decimal.
    config = tomllib.loads(source, parse_float=Decimal)
    print(config["tax_rate"])
    print(type(config["tax_rate"]))

    The custom function must not return a dictionary or list. Keep it deterministic because the parser calls it for every TOML float.

    Handle Invalid TOML

    An invalid document raises tomllib.TOMLDecodeError. Catch the error where you can give the user a clear configuration message. Python 3.14 exposes message, document, position, line, and column details on this exception.

    Example:

    import tomllib
    
    try:
        with open("app.toml", "rb") as file:
            config = tomllib.load(file)
    except FileNotFoundError:
        print("Configuration file was not found.")
    except tomllib.TOMLDecodeError as error:
        # Python 3.14 provides line and column attributes.
        line = getattr(error, "lineno", "unknown")
        column = getattr(error, "colno", "unknown")
        print(f"Invalid TOML at line {line}, column {column}: {error}")

    Validate Configuration After Parsing

    Successful parsing proves that the syntax is valid, not that the settings are suitable for your program. Check required sections, allowed values, numeric ranges, file paths, and secrets after loading the document.

    • Keep secrets outside files committed to source control.
    • Set a size limit before accepting untrusted TOML input.
    • Reject unknown or misspelled critical settings when practical.
    • Report a clear field path when validation fails.

    Conclusion

    Python tomllib gives you a dependable standard-library parser for TOML configuration. Open files in binary mode, use loads() for strings, handle decoding errors, and validate the resulting dictionary for your application. Use parse_float when precise decimal conversion matters, and choose a separate library if you need to write TOML.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.