Skip to main content

Type-Driven Development for Python: Automatic Extraction of HOCON Parsers for Python Types

Project description

pytyped-hocon

pytyped-hocon is a Python package that enables automatic extraction of HOCON parsers for given Python types. pytyped-hocon is built on top of pyhocon and pytyped-macros to automatically parse HOCON config files into native Python types. pytyped-hocon is a piece of the pytyped collection of packages and follows its philosophy of using types to automate mundane and repetitive tasks.

Installation

You can install pytyped-hocon from PyPI:

pip install pytyped-hocon

pytyped-hocon is checked on Python 3.6+.

Why pytyped-hocon?

Based on the foundation of pytyped-macros, to our knowledge, pytyped-hocon is the only Python package that supports type-based HOCON parser extraction for all typing combinators including even recursive types that, up to this day, are not even fully supported by Python itself. Additionally, pytyped-hocon is designed to be extensible. That is, you can add your own specialized HOCON parsers for either a simple type or even a generic type.

Currently, pytyped-hocon supports the following type driven HOCON parser extractions:

  • HOCON parsers for basic types such as int, bool, date, datetime, str, and Decimal.
  • HOCON parsers for simple type combinators such as List[T] and Dict[A, B].
  • HOCON parsers for named product types such as NamedTuples or dataclasses.
  • HOCON parsers for anonymous product types such as Tuple[T1, T2, ...].
  • HOCON parsers for anonymous union types such as Optional[T], Union[T1, T2, ...], etc.
  • HOCON parsers for named union types such as class hierarchies (i.e., when a class A has several subclasses A1, ..., An).
  • HOCON parsers for generic types and type variables.
  • HOCON parsers for custom functional types such as Set[T], Secret[T], etc where a custom function is defined for generic types such as Set or Secret and that functional is applied to all instantiations of those generic type.
  • HOCON parsers for recursive types such as binary trees, etc.

Using pytyped-hocon to extract HOCON decoders

First, define your type. For example, the following defines the configuration of a simple new archiver program that connects to a news server, gets today's news and stores it in a database.

from dataclasses import dataclass
from typing import Generic, Optional, TypeVar


T = TypeVar("T")


@dataclass
class Secret(Generic[T]):
    value: T

    def __str__(self) -> str:
        return "<redacted-secret>"

    def __repr__(self) -> str:
        return "<redacted-secret>"


@dataclass
class ServerConfig:
    host: str
    port: Optional[int]  # If None, use port 80
    api_key: Secret[str]
    path: Optional[str]


@dataclass
class DbConfig:
    host: str
    user_name: str
    password: Secret[str]
    port: int = 5432  # Default Postgres port


@dataclass
class ArchiverConfig:
    news_server: ServerConfig
    db: DbConfig

Second, use an instance of AutoHoconParser to extract a HOCON parser as below:

from pytyped.hocon.parser import AutoHoconParser, HoconMappedParser, HoconParser

_auto_hocon_parser = AutoHoconParser()

_auto_hocon_parser.add_custom_functional_type(Secret, lambda t_parser: HoconMappedParser(t_parser, lambda s: Secret(s)))
config_parser: HoconParser[ArchiverConfig] = _auto_hocon_parser.extract(ArchiverConfig)

Third, define a file such as archiver.conf which contains your program configuration:

archiver: {
    news_server: {
        host: yahoo.com
        api_key: ${YAHOO_API_KEY}
        path: "/news"
    }
    db: {
        host: localhost
        user_name: news
        password: ${DB_PASSWORD}
    }
}

Finally, use config_parser to parse your config file into your config object:

>>> import os
>>> os.environ["YAHOO_API_KEY"] = "secret-api-key"
>>> os.environ["DB_PASSWORD"] = "ABCD"
>>> conf = config_parser.from_file("archiver.conf", root="archiver")
>>> conf
ArchiverConfig(
    news_server=ServerConfig(
        host='yahoo.com',
        port=None,
        api_key=<redacted-secret>,
        path='/news'
    ),
    db=DbConfig(
        host='localhost',
        user_name='news',
        password=<redacted-secret>,
        port=5432
    )
)
>>> conf.news_server.api_key.value
'secret-api-key'
>>> conf.db.password.value
'ABCD'

Issues

Please report any issues to the GitHub repository for this package.

Contributors

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytyped-hocon-1.0.0.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

pytyped_hocon-1.0.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file pytyped-hocon-1.0.0.tar.gz.

File metadata

  • Download URL: pytyped-hocon-1.0.0.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.9.16

File hashes

Hashes for pytyped-hocon-1.0.0.tar.gz
Algorithm Hash digest
SHA256 8c325c8fe542fe1687e2d16aac2ad9f95334c0a95feee4a72e96b3e6c79ed570
MD5 143fb1c5e67329195cc2a73aa32b951b
BLAKE2b-256 bf3608c47c9038890ad903a9ec19c0844f32bfaff53a499528bd8434e182c952

See more details on using hashes here.

File details

Details for the file pytyped_hocon-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pytyped_hocon-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3e5a8b374c2f0b2b5092c9a05cb9c1e5fb70443939259201c3df4a75490b9016
MD5 fe3086401ed4a3e8f584b34120e536ff
BLAKE2b-256 5b7ff14cad0653b900453b50cde0cd4cadcf904189f6cff92dfb8bd885858506

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page