Top Related Projects
Quick Overview
The uiri/toml
repository is a Python library that provides a parser and serializer for the TOML (Tom's Obvious, Minimal Language) configuration file format. TOML is a human-readable data format that is designed to be easy to write and read, and is often used for configuration files in software projects.
Pros
- Robust and Reliable: The
uiri/toml
library is well-tested and has been actively maintained since its initial release, ensuring a stable and reliable implementation of the TOML specification. - Comprehensive Functionality: The library supports both parsing and serializing TOML data, making it a versatile tool for working with TOML files in Python projects.
- Flexible and Extensible: The library provides a range of options and customization points, allowing users to tailor its behavior to their specific needs.
- Actively Maintained: The project has a responsive maintainer who regularly addresses issues and merges pull requests, ensuring the library remains up-to-date and compatible with the latest TOML specification.
Cons
- Limited Language Support: The
uiri/toml
library is primarily focused on Python, and does not provide direct support for other programming languages, which may limit its usefulness in multi-language projects. - Potential Performance Concerns: While the library is generally fast and efficient, it may not be the optimal choice for processing extremely large TOML files, as it loads the entire file into memory before parsing.
- Lack of Advanced Features: The library provides a basic set of features for working with TOML data, but may not offer more advanced functionality, such as support for custom data types or complex validation rules.
- Potential Compatibility Issues: As the TOML specification continues to evolve, there is a risk that the library may not immediately support the latest version, potentially causing compatibility issues for users.
Code Examples
Here are a few examples of how to use the uiri/toml
library in Python:
- Parsing a TOML file:
import toml
with open('example.toml', 'r') as f:
data = toml.load(f)
print(data)
This code reads a TOML file named example.toml
and parses its contents into a Python dictionary.
- Serializing a Python dictionary to TOML:
import toml
data = {
'name': 'John Doe',
'age': 42,
'hobbies': ['reading', 'hiking', 'photography']
}
toml_string = toml.dumps(data)
print(toml_string)
This code takes a Python dictionary and serializes it to a TOML string.
- Handling TOML data with custom types:
import toml
from datetime import datetime
class CustomType:
def __init__(self, value):
self.value = value
def custom_type_encoder(obj):
if isinstance(obj, CustomType):
return {'__custom_type__': 'CustomType', 'value': obj.value}
else:
return obj
def custom_type_decoder(obj):
if '__custom_type__' in obj:
if obj['__custom_type__'] == 'CustomType':
return CustomType(obj['value'])
return obj
data = {
'name': 'John Doe',
'custom_value': CustomType(42)
}
toml_string = toml.dumps(data, default=custom_type_encoder)
print(toml_string)
loaded_data = toml.loads(toml_string, object_hook=custom_type_decoder)
print(loaded_data)
This example demonstrates how to handle custom data types when working with TOML data, by providing custom encoder and decoder functions.
Getting Started
To get started with the uiri/toml
library, you can install it using pip:
pip install toml
Once installed, you can start using the library in your Python code. Here's a simple example of how to read and write TOML data:
import toml
# Write TOML data
data = {
'name': 'John Doe',
Competitor Comparisons
Tom's Obvious, Minimal Language
Pros of toml-lang/toml
- Official TOML specification repository, providing the authoritative reference
- Includes comprehensive test suites for TOML implementations
- Offers detailed documentation and examples for TOML usage
Cons of toml-lang/toml
- Not a parser or implementation, only a specification
- May have slower updates due to the need for consensus among maintainers
Code comparison
toml-lang/toml (TOML example):
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
uiri/toml (Python parsing example):
import toml
config = toml.load("config.toml")
print(config["owner"]["name"])
print(config["database"]["ports"])
Summary
toml-lang/toml serves as the official TOML specification, providing a comprehensive reference and test suite for TOML implementations. It's ideal for understanding TOML syntax and ensuring compliance. However, it's not a parser or implementation itself.
uiri/toml, on the other hand, is a Python library for parsing TOML files. It offers practical functionality for working with TOML in Python projects but may not always be up-to-date with the latest TOML specification changes.
Choose toml-lang/toml for reference and specification needs, and uiri/toml for Python-based TOML parsing and manipulation.
Go library for the TOML file format
Pros of go-toml
- Better performance, especially for large TOML files
- More comprehensive feature set, including encoding/decoding and query support
- Active development with frequent updates and bug fixes
Cons of go-toml
- More complex API, which may be overkill for simple use cases
- Larger codebase and dependencies, potentially increasing project size
Code Comparison
toml:
type Config struct {
Name string
Age int
}
var conf Config
_, err := toml.Decode(tomlData, &conf)
go-toml:
type Config struct {
Name string
Age int
}
var conf Config
err := toml.Unmarshal([]byte(tomlData), &conf)
Both libraries offer similar basic functionality for parsing TOML data into Go structs. However, go-toml provides additional methods for more advanced use cases, such as querying and modifying TOML data:
tree, _ := toml.Load(tomlData)
value := tree.Get("database.server")
tree.Set("database.port", 8080)
While toml focuses on simplicity and ease of use, go-toml offers a more feature-rich experience at the cost of increased complexity. The choice between the two depends on the specific requirements of your project and the level of TOML manipulation needed.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
TOML
.. image:: https://img.shields.io/pypi/v/toml :target: https://pypi.org/project/toml/
.. image:: https://travis-ci.org/uiri/toml.svg?branch=master :target: https://travis-ci.org/uiri/toml
.. image:: https://img.shields.io/pypi/pyversions/toml.svg :target: https://pypi.org/project/toml/
A Python library for parsing and creating TOML <https://en.wikipedia.org/wiki/TOML>
_.
The module passes the TOML test suite <https://github.com/toml-lang/toml-test>
_.
See also:
The TOML Standard <https://github.com/toml-lang/toml>
_The currently supported TOML specification <https://github.com/toml-lang/toml/blob/v0.5.0/README.md>
_
Installation
To install the latest release on PyPI <https://pypi.org/project/toml/>
_,
simply run:
::
pip install toml
Or to install the latest development version, run:
::
git clone https://github.com/uiri/toml.git cd toml python setup.py install
Quick Tutorial
toml.loads takes in a string containing standard TOML-formatted data and returns a dictionary containing the parsed data.
.. code:: pycon
import toml toml_string = """ ... # This is a TOML document. ... ... title = "TOML Example" ... ... [owner] ... name = "Tom Preston-Werner" ... dob = 1979-05-27T07:32:00-08:00 # First class dates ... ... [database] ... server = "192.168.1.1" ... ports = [ 8001, 8001, 8002 ] ... connection_max = 5000 ... enabled = true ... ... [servers] ... ... # Indentation (tabs and/or spaces) is allowed but not required ... [servers.alpha] ... ip = "10.0.0.1" ... dc = "eqdc10" ... ... [servers.beta] ... ip = "10.0.0.2" ... dc = "eqdc10" ... ... [clients] ... data = [ ["gamma", "delta"], [1, 2] ] ... ... # Line breaks are OK when inside arrays ... hosts = [ ... "alpha", ... "omega" ... ] ... """ parsed_toml = toml.loads(toml_string)
toml.dumps takes a dictionary and returns a string containing the corresponding TOML-formatted data.
.. code:: pycon
new_toml_string = toml.dumps(parsed_toml) print(new_toml_string) title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002,] connection_max = 5000 enabled = true [clients] data = [ [ "gamma", "delta",], [ 1, 2,],] hosts = [ "alpha", "omega",] [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10"
toml.dump takes a dictionary and a file descriptor and returns a string containing the corresponding TOML-formatted data.
.. code:: pycon
with open('new_toml_file.toml', 'w') as f: ... new_toml_string = toml.dump(parsed_toml, f) print(new_toml_string) title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002,] connection_max = 5000 enabled = true [clients] data = [ [ "gamma", "delta",], [ 1, 2,],] hosts = [ "alpha", "omega",] [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10"
For more functions, view the API Reference below.
Note
For Numpy users, by default the data types np.floatX
will not be translated to floats by toml, but will instead be encoded as strings. To get around this, specify the TomlNumpyEncoder
when saving your data.
.. code:: pycon
import toml import numpy as np a = np.arange(0, 10, dtype=np.double) output = {'a': a} toml.dumps(output) 'a = [ "0.0", "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "7.0", "8.0", "9.0",]\n' toml.dumps(output, encoder=toml.TomlNumpyEncoder()) 'a = [ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,]\n'
API Reference
toml.load(f, _dict=dict)
Parse a file or a list of files as TOML and return a dictionary.
:Args:
* f
: A path to a file, list of filepaths (to be read into single
object) or a file descriptor
* _dict
: The class of the dictionary object to be returned
:Returns:
A dictionary (or object _dict
) containing parsed TOML data
:Raises:
* TypeError
: When f
is an invalid type or is a list containing
invalid types
* TomlDecodeError
: When an error occurs while decoding the file(s)
toml.loads(s, _dict=dict)
Parse a TOML-formatted string to a dictionary.
:Args:
* s
: The TOML-formatted string to be parsed
* _dict
: Specifies the class of the returned toml dictionary
:Returns:
A dictionary (or object _dict
) containing parsed TOML data
:Raises:
* TypeError
: When a non-string object is passed
* TomlDecodeError
: When an error occurs while decoding the
TOML-formatted string
toml.dump(o, f, encoder=None)
Write a dictionary to a file containing TOML-formatted data
:Args:
* o
: An object to be converted into TOML
* f
: A File descriptor where the TOML-formatted output should be stored
* encoder
: An instance of TomlEncoder
(or subclass) for encoding the object. If None
, will default to TomlEncoder
:Returns:
A string containing the TOML-formatted data corresponding to object o
:Raises:
* TypeError
: When anything other than file descriptor is passed
toml.dumps(o, encoder=None)
Create a TOML-formatted string from an input object
:Args:
* o
: An object to be converted into TOML
* encoder
: An instance of TomlEncoder
(or subclass) for encoding the object. If None
, will default to TomlEncoder
:Returns:
A string containing the TOML-formatted data corresponding to object o
Licensing
This project is released under the terms of the MIT Open Source License. View LICENSE.txt for more information.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot