Skip to main content

Python utils and configuration

  1. Configuration
  2. Safe type convertors
  3. Compress
  4. DateTime
  5. Concurrency
  6. Stats collector
  7. Dependency injection

1. Configuration

Constants and variables

Config files can be set via CONFIG environ var or passed directly to Config() (argument takes priority). Config string contains absolute paths to files separated by ;, later files override earlier ones. Relative paths are not supported (use DirConfig for directories).

export CONFIG='/path/to/base_config.toml;/path/to/config.toml'
from ttutils import Config

CFG = Config()  # get config path from CONFIG environ
CFG = Config('/path/to/config.toml')  # or pass directly

CFG.PUBLIC_URL  # get from config files
CFG.ENV.CONFIG  # get from os env
CFG.SECRET.KEY  # get from os env and clean

Logging configuration

Logging config files can be set via LOGGING environ var or passed directly to LoggingConfig() (argument takes priority). Config string contains absolute paths to files separated by ;. Relative paths are not supported. extra_config updates sections after files, apply_config (default True) applies config via dictConfig.

export LOGGING='/path/to/logging.toml'
from ttutils import LoggingConfig

LoggingConfig('/path/to/logging.toml', extra_config={
    'loggers': {
        'aiohttp.access': {  # local overriding
            'level': 'ERROR',
        }
    }
})

Config file selection

config argument CONFIG env loaded files
not set files files as is (with ;)
not set not set ConfigError
not set dir ConfigError (use DirConfig)
set ('/abs/path.toml') any /abs/path.toml as is
set ('/a.toml;b.toml') any both files (with ;)
set (relative) any ConfigError (only absolute paths)

LoggingConfig file selection

config argument LOGGING env loaded files
not set files files as is (with ;)
not set not set ConfigError
set ('/abs/log.toml') any /abs/log.toml as is
set (relative) any ConfigError (only absolute paths)

Configuration from directory

DirConfig loads configs from a directory specified by CONFIG environ var (must be an existing directory). Relative file names are resolved against it.

export CONFIG='/path/to/config_dir'
ls /path/to/config_dir
base.toml     <-- loaded by DirConfig (alphabetical order)
logging.toml  <-- applied via LoggingConfig
from ttutils import DirConfig

CFG = DirConfig()                      # all toml-files except `logging` in name; `*logging*` applied via LoggingConfig
CFG = DirConfig('db.toml;redis.toml')  # only specified files, `*logging*` still applied
CFG = DirConfig('', 'access.toml')     # only specified log config

DirConfig file selection

config arg log_config arg loaded files
not set not set all toml except *logging*; *logging* via LoggingConfig
'db.toml;redis.toml' not set only specified files; all *logging* via LoggingConfig
not set 'access.toml' all toml except *logging*; only access.toml via LoggingConfig
'db.toml' 'access.toml' only specified files; only access.toml via LoggingConfig

Environ var name can be overridden per class with set_env_name:

Config.set_env_name('MYCONFIG')        # Config and DirConfig now read MYCONFIG
LoggingConfig.set_env_name('MYLOGGING')

2. Safe type convertors

from ttutils import try_int, as_bool, to_string, safe_text, text_crop, int_list, int_set

try_int('123') == 123
try_int('asd') is None

as_bool('t') is True
as_bool(1) is True
as_bool('false') is False

to_string(AClass) == '<AClass>'
to_string('text') == 'text'
to_string(b'text') == 'text'

to_bytes('text') == b'text'
to_bytes(b'text') == b'text'
to_bytes(1234567890) == b'I\x96\x02\xd2'

safe_text('<b>text</b>') == '&lt;b&gt;text&lt;/b&gt;'
safe_text('text') == 'text'

text_crop('text', 5) == 'text'
text_crop('sometext', 6) == 'some …'

int_list(['1', '2', 'a', 'b', None]) == [1, 2]
int_set(['1', '2', 'a', 'b', None]) == {1, 2}

3. Compress

Integer, dict integers, list integers compression/decompression functions

from ttutils import compress

compress.encode(11232423)  # 'GSiD'
compress.decode('GSi')  # 175506

compress.encode_list([12312, 34535, 12323])  # '30o-8rD-30z'
compress.decode_list('30o-8rD-30z--30C')  # [12312, 34535, 12323, 12324, 12325, 12326]

compress.encode_dict({12: [234, 453], 789: [12, 98, 99, 100, 101]})  # 'c-3G-75/cl-c-1y--1B'
compress.decode_dict('c-3G-75/cl-c-1y--1B')  # {12: [234, 453], 789: [12, 98, 99, 100, 101]}

4. DateTime

Datetime parse and serialize utils

from ttutils import (utcnow, utcnow_ms, utcnow_sec, parsedt, parsedt_ms,
    parsedt_sec, try_parsedt, isoformat, safe_isoformat)

utcnow()      # datetime(2022, 2, 22, 14, 28, 10, 158164, tzinfo=datetime.UTC)
utcnow_ms()   # datetime(2022, 2, 22, 14, 28, 20, 824000, tzinfo=datetime.UTC)
utcnow_sec()  # datetime(2022, 2, 22, 14, 28, 24, tzinfo=datetime.UTC)

parsedt('2022-02-22T11:22:33.123456Z')      # datetime(2022, 2, 22, 11, 22, 33, 123456, tzinfo=datetime.UTC)
parsedt_ms('2022-02-22T11:22:33.123456Z')   # datetime(2022, 2, 22, 11, 22, 33, 123000, tzinfo=datetime.UTC)
parsedt_sec('2022-02-22T11:22:33.123456Z')  # datetime(2022, 2, 22, 11, 22, 33, tzinfo=datetime.UTC)

try_parsedt('2022-02-22T11:22:33.123456Z')  # datetime(2022, 2, 22, 11, 22, 33, 123456, tzinfo=datetime.UTC)
try_parsedt(None)  # None

isoformat(utcnow())      # '2022-02-22T14:33:51.381164Z'
try_isoformat(utcnow())  # '2022-02-22T14:33:51.381164Z'
try_isoformat(None)      # None

5. Concurrency

Tools for asyncio

To limit the parallelism of an asynchronous function, install a decorator

from ttutils import concurrency_limit

@concurrency_limit(2)
async def my_task(...) -> None:
    ...  # there are only 2 concurrent executions

# the queue length will be recorded in the log when the function is overloaded
log = logging.getLogger('concurrency_logger')

@concurrency_limit(2, logger=log)
async def my_task(...) -> None:
    ...  # there are only 2 concurrent executions

6. Stats collector

The Collector is designed for:

  • collecting execution time data for functions, methods and code blocks,
  • generating periodic reports on execution time statistics,
  • keeping a log of slow requests.
from ttutils.stats import Collector

stats = Collector()

@stats.atimer('k1')
async def func():
   ...

class A:
   @stats.atimer('k2')
   async def func(self):
       ...

with stats.timer('k3'):
   sync_func()
   await async_func()

7. Dependency injection

Lightweight DI: a pool of ready-made objects («resources») and a single set of rules for filling class fields from it and assembling dependency chains. No framework coupling, no scopes or lifecycles — the container is created per assembly point and is one-shot.

Two scenarios:

  • build() — create a dataclass object from scratch;
  • inject() — fill in an already existing object based on its annotations.
from dataclasses import dataclass
from ttutils import Resources, Injectable

@dataclass
class Store:
    db: Database      # types are taken from the pool
    cache: Cache

@dataclass
class Handler:
    store: Store      # dataclass field is assembled recursively

db, cache = Database(...), Cache(...)

# build from scratch
handler = Resources({'db': db, 'cache': cache}).build(Handler)

# fill in an existing object
class View:
    store: Store

view = View()
Resources({'db': db, 'cache': cache}).inject(view)

# mixin — self.inject() without creating a container
class Agent(Injectable):
    handler: Handler
    db: Database

agent = Agent()
agent.db = Database(dsn='...', pool_size=5)  # manual assembly: special parameters
agent.inject({'cache': cache})               # handler will be assembled: db — from the instance,
                                             # cache — from the pool

Field resolution order

The same for any field — both plain and dataclass:

# Source Example
1 By name — name in pool 'replica': db2 — overrides type-match
2 By type — an object of that type in the pool field db: Database → the only Database in the pool
3 Recursive build — dataclass field store: Store → Store(db=..., cache=...)
4 Config fallback — the first Mapping in the pool scalar page_size: int → pool['config']['page_size']
5 Skip — field keeps its default the field must have a default or be Optional
@dataclass
class Service:
    db: Database            # → step 2 (by type)
    replica: Database       # → step 1 (by name: 'replica' is in the pool)
    page_size: int = 25     # → step 4 (from the Mapping in the pool)
    timeout: float = 1.0    # → step 5 (nowhere to be found) — keeps the default

svc = Resources({
    'db': Database(...),
    'replica': Database(...),
    'config': {'page_size': 50},   # a plain Mapping is enough
}).build(Service)

Filling in: the inject() rule

What is already set on the instance is left untouched but becomes a resource for assembling the remaining fields. This makes it possible to mix manual and declarative assembly; a repeated inject() on the same object is safe (no-op).

Field state Behavior
Set on the instance fixed as is (even None)
Class default overridden by the pool; if not found — stays
Neither value nor default resolved from the pool; if not found — skipped

The Injectable mixin has no annotations of its own and is safe to inherit from dataclass classes (dataclass base goes first: class Agent(BaseDataclass, Injectable)).

Validation

All assignments are checked with a strict isinstance against the annotation — including already set values and class defaults. A type error is a DIError raised at assembly time, not a silent failure later; assembly errors contain the full path along the dependency chain.

Resources({'db': 'not_a_database'}).build(Service)
# DIError: `Service -> db` has type `str`, expected `Database`

Limitations

  • build() works only with dataclass classes; for everything else use a constructor + inject().
  • The first Mapping object in the pool acts as the config source — do not put non-config Mappings into the pool.
  • Fields not resolved from the pool are silently skipped — they must have defaults; missing required arguments will surface as DIError: Build failed for ....
  • Cyclic dependencies (a field of the class's own type) are not supported.

Metadata

Release files for ttutils 0.13

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ttutils 0.13
File Size Uploaded Provenance Actions
ttutils-0.13.tar.gz 32.6 kB Without provenance Details for ttutils-0.13.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ttutils 0.13
File Interpreter ABI Platform Actions
ttutils-0.13-py3-none-any.whl Python 3 none any Details for ttutils-0.13-py3-none-any.whl

Total release size: 55.5 kB

Release files / ttutils-0.13.tar.gz

Download URL ttutils-0.13.tar.gz
Size 32.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ac3ab430ea2fb44f4de6ca4d04c78c527a65c7d1431a9037b1111286788175cd
BLAKE2b-256 checksum
How to use checksums
cd6b507638aeddfd474de035745a229280e80c30e6cf5d1889a2213451e8095f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.10

Release files / ttutils-0.13-py3-none-any.whl

Download URL ttutils-0.13-py3-none-any.whl
Size 22.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f37ddd5c9803f1f5a44eebe5dcea60fb71e676167e999697efca0643e7c617b6
BLAKE2b-256 checksum
How to use checksums
90eb569cc782a987dae73724f0b7f480dbc2375d0e71bba98b42906c2230fa3a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.10

Security for ttutils 0.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page