Skip to main content

Essential Python utilities for console, math, system, and more

Project description

Py-Utils – Essential Python Utilities

Python Version License

A collection of battle‑tested utility modules for everyday Python tasks: console interaction, file dialogs, precise arithmetic, data handling, string formatting, system operations, and more.

Designed to be lightweight, self‑contained, and easy to integrate into any project.


📦 Installation

pip install py-utils 

Or using UV:

uv add py-utils

Or clone & install manually:

git clone https://github.com/codigomex/Py-Utils.git
cd py_utils
pip install -e .

🚀 Quick Start

from swiss_utils.console import pparr, ask_type, clear
from swiss_utils.math import div_prec, precise_round
from swiss_utils.system import show_tmp, init_tmp

# Or you can import everything using (eg):
# from py_utils import div_prec, init_tmp, pparr, etc.

# Clear terminal and print formatted message
clear()
pparr("Hello, world!", indent=">>> ")

# Safe division with decimal precision
result = div_prec(10, 3, precision=4)
print(result)  # 3.3333

# Round with specific rounding mode
rounded = precise_round(2.675, decimals=2)   # 2.68 (ROUND_HALF_UP)

# Show any text in a temporary file (opens in system editor)
init_tmp()
show_tmp("Important data\nLine 2", wait=True)

📚 Module Overview

Module Description
config Global constants: OS detection, temp dir, ANSI escape, terminal width.
console Interactive I/O: progress bar, waiting dots, user input validation, dates.
data Dictionary comparison, UUID‑like token generator, pretty data display.
format Random strings, ANSI stripping, time formatting, terminal colors (cl).
forms Tkinter file & directory dialogs (returns Path or None).
math High‑precision rounding, division (with configurable precision), time‑to‑seconds.
py @immutable decorator – make class instances read‑only after __init__.
system File execution, temp file handling, error traceback, user input via editor.
units Convert between pixels, mm, points, inches – exact Decimal results.

🧩 Detailed Examples

1. Console & User Input

# swiss_utils.console
from py_utils import ask_verif, ask_date, op_yn, draw_progress_bar

# Yes/No prompt
if op_yn():
    print("User agreed")

# Validate from a set of answers
color = ask_verif("Choose color:", "red", "green", "blue")

# Date input (no future dates allowed)
date = ask_date("Enter birth date (YYYY-MM-DD):", fmt="%Y-%m-%d", future=False)

# Progress bar
for p in range(0, 101, 10):
    draw_progress_bar(p)

2. Immutable Classes

# swiss_utils.py
from py_utils import immutable

@immutable
class Config:
    def __init__(self, host, port):
        self.host = host
        self.port = port

cfg = Config("localhost", 8080)
cfg.host = "other"   # ❌ raises AttributeError

3. Precise Arithmetic

# swiss_utils.math
from py_utils import div_prec, precise_round
from decimal import ROUND_DOWN

# Division with 6 decimal places
result = div_prec(22, 7, precision=6)   # 3.142857

# Round with custom mode
rounded = precise_round(3.14159, decimals=4, rounding_mode=ROUND_DOWN)  # 3.1415

4. Temporary Files / System

# swiss_utils.system
from py_utils import init_tmp, show_tmp, get_user_input

init_tmp(delete=True)          # clean previous temp dir

# Open a text file for long user input
lines = get_user_input("Describe the problem in detail:")
print(f"You wrote {len(lines)} lines")

# Show dictionary/object dump in a temp file
show_tmp("Debug info:\n" + str(some_dict), wait=False)

5. File Dialogs (no extra GUI loops)

# swiss_utils.forms
from py_utils import pic_dir, pic_file

folder = pic_dir(Path.home())      # returns Path or None
file   = pic_file(Path.cwd(), ext="json")

6. Colors & Formatting

# swiss_utils.format
from py_utils import cl

print(f"{cl.bgreen}Success!{cl.endc}")
print(f"{cl.red}Error:{cl.endc} Something went wrong")

🛠 Development & Testing

# Run all tests (if you add a tests/ folder)
pytest tests/

# Static type check
mypy py_utils/

🤝 Contributing

Pull requests are welcome @codigomex! For major changes, please open an issue first.

📄 License

GPL‑3.0 © CodigoMex

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

swiss_utils-1.0.0.tar.gz (30.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swiss_utils-1.0.0-py3-none-any.whl (28.1 kB view details)

Uploaded Python 3

File details

Details for the file swiss_utils-1.0.0.tar.gz.

File metadata

  • Download URL: swiss_utils-1.0.0.tar.gz
  • Upload date:
  • Size: 30.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for swiss_utils-1.0.0.tar.gz
Algorithm Hash digest
SHA256 a22d5974158bb8f1bf1bce35f2b9b7fdbb54eee3d0e97297fadb90c77b9224a2
MD5 13fa59e417c2a4068302a7e3035604fc
BLAKE2b-256 dbd5d8e56196d10f855d13d7b66037b1241023736baa9a4c7729c2a5942b18ca

See more details on using hashes here.

File details

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

File metadata

  • Download URL: swiss_utils-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 28.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for swiss_utils-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2b68226e14b815d50dfebb20fd159edc4188612da6e68531b93f9d4197e49784
MD5 1c2b6658d5db55b691e5906e3a136651
BLAKE2b-256 faebf288380ec1b2dd2fb97a767b525c1563cef6d711e8e06636b9aebc602ded

See more details on using hashes here.

Supported by

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