PyCoke

The Ultimate Python Utility Module for Modern Development

Streamline your Python workflow with a comprehensive collection of efficient, reliable, and well-tested utilities.

pip install PyCoke
import pycoke as pc

# Safe type conversion
num = pc.safe_cast("123", int, fallback=0)

# Input handling
name = pc.safe_input("Enter your name: ", str, "Guest")

# Data validation
if pc.validate_email("user@example.com"):
    print("Valid email!")

# And much more...

Powerful Features

Everything you need to supercharge your Python development

Safe Casting & Parsing

Convert and validate data effortlessly with built-in fallback mechanisms and robust error handling.

Input Handling

Safely capture and process user inputs with comprehensive validation and type conversion.

Validation Utilities

Quickly validate data like emails, phone numbers, and passwords using industry-standard patterns.

Error Handling & Logging

Execute code safely, log errors, and retry operations with configurable parameters.

Data Helpers

Flatten, chunk, and deduplicate lists with optimized algorithms for better performance.

String Helpers

Clean, normalize, and manipulate strings with full Unicode support and edge case handling.

File & OS Utilities

Safely manage files and paths with proper error handling and permission checks.

Networking Utilities

Make reliable network requests with timeout handling and retry mechanisms.

See PyCoke in Action

Explore practical examples of how PyCoke can simplify your code.

from pycoke import safe_cast, parse_json

# Convert string to int, with a fallback
num = safe_cast("123a", int, fallback=-1)
# Returns: -1

# Parse JSON safely
data = parse_json('{"name": "John",}', fallback={})
# Returns: {} because of trailing comma
from pycoke import safe_input, ask_yes_no

# Get user age, ensuring it's an integer
age = safe_input("Enter your age: ", int, 18)

# Ask a yes/no question
if ask_yes_no("Proceed with caution?"):
    print("Continuing...")
from pycoke import validate_email, validate_password

# Validate an email address
validate_email("contact@example.com")
# Returns: True

# Check for a strong password
validate_password("Password123!")
# Returns: True
from pycoke import flatten_list, chunk_list

# Flatten a nested list
nested = [1, [2, 3], [4, [5]]]
flatten_list(nested)
# Returns: [1, 2, 3, 4, 5]

# Split a list into smaller chunks
chunk_list(range(10), 3)
# Returns: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
from pycoke import safe_exec, retry, log_error

# Safely execute a function with a fallback
result = safe_exec(lambda: 1 / 0, fallback="division-by-zero")
# Returns: "division-by-zero"

# Retry a flaky operation up to 3 times
counter = {"i": 0}
def sometimes_fails():
    counter["i"] += 1
    if counter["i"] < 3:
        raise ValueError("Try again")
    return "ok"

retry_result = retry(sometimes_fails, attempts=3, delay=1)
# Returns: "ok" on third attempt

# Log an error to file
try:
    1/0
except Exception as e:
    log_error(e, message="Computation failed")
from pycoke import slugify, truncate, normalize_whitespace, safe_strip

slug = slugify("Hello, World! PyCoke v1.0")
# "hello-world-pycoke-v1-0"

short = truncate("This is a very long message", 12)
# "This is a ve..."

clean = normalize_whitespace("a   b\n c\t d")
# "a b c d"

safe = safe_strip(None)
# ""
from pycoke import safe_read, safe_write, file_exists, safe_delete

ok = safe_write("/tmp/pycoke_demo.txt", "Hello PyCoke!\n")
content = safe_read("/tmp/pycoke_demo.txt", fallback="")
exists = file_exists("/tmp/pycoke_demo.txt")
removed = safe_delete("/tmp/pycoke_demo.txt")

# ok -> True, content -> "Hello PyCoke!\n", exists -> True, removed -> True
from pycoke import is_internet_available, safe_get

online = is_internet_available(timeout=2)
page = safe_get("https://httpbin.org/get", fallback="")

# online -> True/False depending on connectivity
# page -> response text or "" on error
from pycoke import is_numeric, to_bool, validate_number_range, validate_phone, unique_list, safe_dict_get

# Check numeric strings
is_numeric("12.5")  # True
is_numeric("abc")   # False

# Flexible boolean casting
to_bool("Yes")      # True
to_bool("no")       # False

# Ranged validation
validate_number_range("42", 0, 100)  # True

# Simple phone validation (default +91 country code)
validate_phone("+911234567890")      # True

# Unique elements while preserving order
unique_list([1, 2, 2, 3, 1])  # [1, 2, 3]

# Safe dict get
safe_dict_get({"a": 1}, "b", fallback=0)  # 0