Skip to main content

*("yoots")*: utilities I've missed in the Python standard library

Project description

utz

("yoots"): utilities I've missed in the Python standard library

Install

pip install utz

Use

I usually do this at the top of Jupyter notebooks:

from utz import *

This imports most standard library modules/functions (via stdlb), as well as the utz.* members below.

Some specific modules, in rough order of how often I use them:

utz.process

subprocess wrappers; shell out to commands, parse output:

from utz.process import *

# Run a command
run('git', 'commit', '-m', 'message')  # Commit staged changes

# Return `list[str]` of stdout lines
lines('git', 'log', '-n5', '--format=%h')  # Last 5 commit SHAs

# Verify exactly one line of stdout, return it
line('git', 'log', '-1', '--format=%h')  # Current HEAD commit SHA

# Return stdout as a single string
output('git', 'log', '-1', '--format=%B')  # Current HEAD commit message

# Check whether a command succeeds, suppress output
check('git', 'diff', '--exit-code', '--quiet')  # `True` iff there are no uncommitted changes

err("This will be output to stderr")

See also: test_process.py.

utz.collections

Collection/list helpers:

from utz.collections import *

# Verify a collection has one element, return it
singleton(["aaa"])         # "aaa"
singleton(["aaa", "bbb"])  # error

See also: test_collections.py.

utz.cd: "change directory" contextmanager

from utz import cd
with cd('..'):  # change to parent dir
    ...

utz.ctxs: compose contextmanagers

from utz import *
with ctxs(NamedTemporaryFile(), NamedTemporaryFile()) as (f1, f2):
    ...

See also: test_context.py.

utz.fn

Compose decorators:

from utz import decos
from click import option

common_opts = decos(
    option('-n', type=int),
    option('-v', is_flag=True),
)

@common_opts
def subcmd1(n: int, v: bool):
    ...

@common_opts
def subcmd2(n: int, v: bool):
    ...

Only pass expected kwargs to functions:

from utz.fn import call
def fn1(a, b):
    ...
def fn2(a, c):
    ...
kwargs = dict(a=11, b='22', c=33)
call(fn1, kwargs)  # only pass {a, b}
call(fn2, kwargs)  # only pass {a, c}

utz.plot: Plotly helpers

Helpers for Plotly transformations I make frequently, e.g.:

from utz import plot
import plotly.express as px
fig = px.bar(x=[1, 2, 3], y=[4, 5, 6])
plot(
    fig,
    name='my-plot',  # Filename stem. will save my-plot.png, my-plot.json, optional my-plot.html
    title=['Some Title', 'Some subtitle'],  # Plot title, followed by "subtitle" line(s) (smaller font, just below)
    bg='white', xgrid='#ccc',  # white background, grey x-gridlines
    hoverx=True,  # show x-values on hover
    x="X-axis title",  # x-axis title or configs
    y=dict(title="Y-axis title", zerolines=True),  # y-axis title or configs
    # ...
)

Example usages: hudcostreets/nj-crashes, ryan-williams/arrayloader-benchmarks.

utz.setup: setup.py helper

utz/setup.py provides defaults for various setuptools.setup() params:

  • name: use parent directory name
  • version: parse from git tag (otherwise from git describe --tags)
  • install_requires: read requirements.txt
  • author_{name,email}: infer from last commit
  • long_description: parse README.md (and set long_description_content_type)
  • description: parse first <p> under opening <h1> from README.md
  • license: parse from LICENSE file (MIT and Apache v2 supported)

For an example, see gsmo==0.0.1 (and corresponding release).

This library also "self-hosts" using utz.setup; see pyproject.toml:

[build-system]
requires = ["setuptools", "utz[setup]==0.4.2", "wheel"]
build-backend = "setuptools.build_meta"

and setup.py:

from utz.setup import setup

extras_require = {
    # …
}

# Various fields auto-populated from git, README.md, requirements.txt, …
setup(
    name="utz",
    version="0.8.0",
    extras_require=extras_require,
    url="https://github.com/runsascoded/utz",
    python_requires=">=3.10",
)

The setup helper can be installed via a pip "extra":

pip install utz[setup]

Misc

Other noteworthy modules:

  • o: dict wrapper exposing keys as attrs (e.g.: o({'a':1}).a == 1)
  • docker: DSL for programmatically creating Dockerfiles (and building images from them)
  • ssh: SSH tunnel wrapped in a context manager
  • time: now()/today() helpers with convenient / no-nonsense ISO string serialization and UTC bias
  • bases: intstr codecs with improvements over standard base64 et al.
  • tmpdir: make temporary directories with a specific basename
  • escape: escaping split/join helpers
  • backoff: exponential-backoff utility
  • git: Git helpers, wrappers around GitPython
  • pnds: pandas imports and helpers

Project details


Release history Release notifications | RSS feed

This version

0.9.0

Download files

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

Source Distribution

utz-0.9.0.tar.gz (42.1 kB view details)

Uploaded Source

Built Distribution

utz-0.9.0-py3-none-any.whl (51.5 kB view details)

Uploaded Python 3

File details

Details for the file utz-0.9.0.tar.gz.

File metadata

  • Download URL: utz-0.9.0.tar.gz
  • Upload date:
  • Size: 42.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.15

File hashes

Hashes for utz-0.9.0.tar.gz
Algorithm Hash digest
SHA256 5b1afdd71bd1f1ae47f599f922cddb9b8dd3e7fd8bb21de87b6248fc65000386
MD5 c276d5d9a49d0263870747b590882807
BLAKE2b-256 f5918e80c232639d1b7bfddecb8962527e65da06a181666769018a43cf444a83

See more details on using hashes here.

File details

Details for the file utz-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: utz-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 51.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.15

File hashes

Hashes for utz-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2f6cb7e9d507e6032ae601dbfa953330c2d50129d570e89ea16fc56eb39ec1bc
MD5 c4ec894faeaf1891c6b69516c4ee9350
BLAKE2b-256 cbf2f7ca43a0ddf92f081335a674d0e080bf3a9b5a183fbd0967186f301971de

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