Skip to main content

lkj

Lightweight Kit Jumpstart: small, pure-Python utilities for strings, dicts, iterables, logging, imports and files, with no Python dependencies. Where toolz or more-itertools are libraries you depend on, lkj is a kit you can also copy from: each utility stands on its own.

pip install lkj

Documentation

from lkj import chunker, merge_dicts, camel_to_snake

assert list(chunker(range(7), 3)) == [(0, 1, 2), (3, 4, 5), (6,)]
assert merge_dicts({'a': 1, 'b': {'c': 2}}, {'b': {'d': 3}}) == {'a': 1, 'b': {'c': 2, 'd': 3}}
assert camel_to_snake('HelloWorld') == 'hello_world'

Most modules are self-contained (lkj.strings borrows wrapped_print from lkj.loggers), so you can vendor one by copying the file (do mention the source). Many functions do their own imports, so you can even copy a single function.

What is in the kit

Module Includes
lkj.strings FindReplaceTool, print_list, camel_to_snake, snake_to_camel, indent_lines, truncate_string, fields_of_string_format, regex_based_substitution
lkj.loggers clog (conditional log), print_with_timestamp, print_progress, log_calls, return_error_info_on_error
lkj.dicts merge_dicts (recursive), inclusive_subdict, exclusive_subdict, truncate_dict_values
lkj.iterables compare_sets, get_by_value, index_of
lkj.chunking chunker, chunk_iterable
lkj.importing import_object (from a dot path), import_from_path, register_namespace_forwarding
lkj.filesys get_app_data_dir, search_folder_fast (needs ripgrep), enable_sourcing_from_file

Everything listed is importable from lkj directly.

Examples

Find and replace

FindReplaceTool is a general-purpose find-and-replace tool that can treat the input text as a continuous sequence of characters, even if operations such as viewing context are performed line by line.

The basic usage is

from lkj import FindReplaceTool

FindReplaceTool("apple banana apple").find_and_print_matches(r'apple')
Match 0 (around line 1):
apple banana apple
^^^^^
----------------------------------------
Match 1 (around line 1):
apple banana apple
             ^^^^^
----------------------------------------
FindReplaceTool("apple banana apple").find_and_replace(r'apple', "orange")
'orange banana orange'

See more examples in documentation

Here is an example of how I used this to edit my CI yamls

loggers

clog

Conditional log

>>> from lkj import clog
>>> clog(False, "logging this")
>>> clog(True, "logging this")
logging this

One common usage is when there's a verbose flag that allows the user to specify whether they want to log or not. Instead of having to litter your code with if verbose: statements you can just do this:

>>> verbose = True  # say verbose is True
>>> _clog = clog(verbose)  # makes a clog with a fixed condition
>>> _clog("logging this")
logging this

You can also choose a different log function. Usually you'd want to use a logger object from the logging module, but for this example we'll just use print with some modification:

>>> _clog = clog(verbose, log_func=lambda x: print(f"hello {x}"))
>>> _clog("logging this")
hello logging this

print_with_timestamp

Prints with a timestamp and optional refresh.

  • input: message, and possibly args (to be placed in the message string, sprintf-style)
  • output: Displays the time (HH:MM:SS), and the message
  • use: To be able to track processes (and the time they take)
>>> from lkj import print_with_timestamp
>>> print_with_timestamp('processing element X')
(29)09:56:36 - processing element X

return_error_info_on_error

Decorator that returns traceback and local variables on error.

This decorator is useful for debugging. It will catch any exceptions that occur in the decorated function, and return an ErrorInfo object with the traceback and local variables at the time of the error.

  • func: The function to decorate.
  • caught_error_types: The types of errors to catch.
  • error_info_processor: A function that processes the ErrorInfo object.

Tip: To parametrize this decorator, you can use a functools.partial function.

Tip: You can have your error_info_processor persist the error info to a file or database, or send it to a logging service.

>>> from lkj import return_error_info_on_error, ErrorInfo
>>> @return_error_info_on_error
... def foo(x, y=2):
...     return x / y
...
>>> t = foo(1, 2)
>>> assert t == 0.5
>>> t = foo(1, y=0)
Exiting from foo with error: division by zero
>>> if isinstance(t, ErrorInfo):
...     assert isinstance(t.error, ZeroDivisionError)
...     hasattr(t, 'traceback')
...     assert t.locals['args'] == (1,)
...     assert t.locals['kwargs'] == {'y': 0}

Miscellaneous

chunker

Chunk an iterable into non-overlapping chunks of size chk_size.

chunker(a, chk_size, *, include_tail=True)
>>> from lkj import chunker
>>> list(chunker(range(8), 3))
[(0, 1, 2), (3, 4, 5), (6, 7)]
>>> list(chunker(range(8), 3, include_tail=False))
[(0, 1, 2), (3, 4, 5)]

import_object

Import and return an object from a dot string path.

import_object(dot_path: str)
>>> from lkj import import_object
>>> f = import_object('os.path.join')
>>> from os.path import join
>>> f is join
True

Pretty Printing Lists

The print_list function provides flexible, human-friendly ways to display lists and collections. It supports multiple display styles and can be used in several ways.

Basic Usage

from lkj.strings import print_list

items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

# Different display styles
print_list(items, style='wrapped')      # Automatic line wrapping
print_list(items, style='columns')      # Column format
print_list(items, style='numbered')     # Numbered list
print_list(items, style='bullet')       # Bullet points
print_list(items, style='compact')      # All on one line
print_list(items, style='table')        # Table format

Direct Usage with Customization

# Customize width, separators, and formatting
print_list(items, style='wrapped', max_width=40, sep=' | ')
print_list(items, style='columns', items_per_line=3)
print_list(items, style='numbered', line_prefix='  ')
print_list(items, style='bullet', show_count=False)

# Return string instead of printing
result = print_list(items, style='numbered', print_func=None)
print(result)

Partial Function Factory

When you don't specify the items parameter, print_list returns a partial function that you can reuse:

# Create specialized printers
numbered_printer = print_list(style='numbered', show_count=False)
bullet_printer = print_list(style='bullet', print_func=None)
compact_printer = print_list(style='compact', max_width=60)

# Reuse with different data
numbered_printer(['a', 'b', 'c'])        # Prints: 1. a\n2. b\n3. c
result = bullet_printer(['x', 'y', 'z']) # Returns: '• x\n• y\n• z'
compact_printer(['item1', 'item2'])      # Prints: item1, item2

Convenience Methods

The print_list object provides convenient pre-configured methods:

# Quick access to common styles
print_list.compact(items)    # Compact format, no count
print_list.wrapped(items)    # Wrapped format, no count  
print_list.columns(items)    # Column format, no count
print_list.numbered(items)   # Numbered format, no count
print_list.bullets(items)    # Bullet format, no count

# Specialized methods
data = [['Name', 'Age', 'City'], ['Alice', 25, 'NYC'], ['Bob', 30, 'LA']]
print_list.as_table(data)    # Table with headers
print_list.summary(items)    # Summary for long lists

Advanced Examples

# Table with custom data
data = [['Name', 'Age', 'City'], ['Alice', 25, 'NYC'], ['Bob', 30, 'LA']]
print_list.as_table(data)

# Summary for long lists
long_list = list(range(100))
print_list.summary(long_list, max_items=6)  # Shows: [0, 1, 2, ..., 97, 98, 99]

# Custom print function (e.g., for logging)
def my_logger(msg):
    print(f"[LOG] {msg}")

print_list(items, style='bullet', print_func=my_logger)

# Combine partial with custom parameters
custom_compact = print_list(style='compact', sep=' | ')
custom_compact(items)  # Prints: apple | banana | cherry | date | elderberry | fig

Key Features

  • Multiple Styles: wrapped, columns, numbered, bullet, compact, table
  • Flexible Output: Print directly or return strings with print_func=None
  • Partial Functions: Create reusable printers with pre-configured settings
  • Customizable: Control width, separators, line prefixes, and more
  • Type Safe: Uses Literal types for style validation
  • Self-Contained: No external dependencies beyond Python standard library

The print_list function is perfect for debugging, logging, user interfaces, and any situation where you need to display lists in a readable format.

Metadata

Release files for lkj 0.1.54

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

Source distribution (sdist)

Source distribution for lkj 0.1.54
File Size Uploaded Provenance Actions
lkj-0.1.54.tar.gz 44.1 kB Without provenance Details for lkj-0.1.54.tar.gz

Built distribution (wheel)

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

Total release size: 92.8 kB

Release files / lkj-0.1.54.tar.gz

Download URL lkj-0.1.54.tar.gz
Size 44.1 kB
Tags Source
SHA-256 checksum
How to use checksums
774e4007002f2b09fd9c4f740732160976a4564059b8f350c1526033968704f6
BLAKE2b-256 checksum
How to use checksums
9264dfb7797d0f10124e02fab9e4a9bad6ba94cd0b0244fffa74a0460edd6673
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / lkj-0.1.54-py3-none-any.whl

Download URL lkj-0.1.54-py3-none-any.whl
Size 48.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
32bfb439a141c2d383c43ab7e2973ef2bd9f3c6f3a01d15bc3cbf5535f3b03d1
BLAKE2b-256 checksum
How to use checksums
d53193f2d8a4e3900568b72a391ec6117d0a8fe8c88ff174a556791133d35ba6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for lkj 0.1.54

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.

Release history Release notifications | RSS feed

This release

0.1.54 This release

2 release files No provenance

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