Uma biblioteca inspirada em Rust e Kotlin para lidar com Option, println colorido e utilitários.
Project description
🚀 koruspy
High-Performance Functional Logic Library for Python
Functional programming patterns optimized for mobile environments and SmartIDE
📖 English Documentation
🎯 Overview
koruspy is a functional logic library designed for high performance in resource-constrained environments, particularly mobile devices and SmartIDE. Built with Cython acceleration at its core, koruspy provides robust Option types and native performance optimizations that deliver up to 3x faster execution compared to pure Python implementations.
✨ Key Features
- 🔥 Native Cython Engine - Core functions compiled to C for maximum speed
- 📦 Type-Safe Option Types -
Some(value),Nothing, andAsyncOption(future) - ⚡ 3x Performance Gain - Real mobile benchmarks: 0.017s → 0.006s
- 🔧 Zero-Config Compilation - Built-in
setup_native()for seamless local compilation - 👁️ Accessibility-First Design - ANSI colors optimized for OLED displays and astigmatism
- 📱 Mobile-Optimized - Specifically tuned for SmartIDE and mobile Python environments
🚀 Quick Start
Installation
pip install koruspy
Basic Setup with Native Compilation
import koruspy
# Compile native extensions automatically in your environment
koruspy.setup_native()
from koruspy import Some, Nothing, println
# Your high-performance code here
result = Some(42)
println(result)
📦 Option Module
The Option type provides a type-safe way to handle optional values, eliminating None-related errors.
📊 Collection Module: SomeList (v0.7.0)
The SomeList is a fail-safe implementation of a Python list, inheriting from MutableSequence. It's designed to handle data pipelines without crashing.
- Auto-Normalization: Accepts lists, tuples, sets, generators, or single values and converts them to a stable internal list.
- Method Chaining:
.append(),.extend(), and.insert()returnself, allowing for fluent API calls. - Safe Mapping:
.map(fn)returnsnothingif the function fails, keeping your app running.
from koruspy import SomeList, Some
# Safe chaining and functional operations
res = (SomeList([10, 20])
.append(30)
.map(lambda x: x * 2)
.sum()) # Output: 120
Some(value)
Represents a value that exists:
from koruspy import Some, println
user_name = Some("Alice")
println(user_name) # Output: Some(Alice)
# Pattern matching
match user_name:
case Some(name):
println(f"Hello, {name}!")
case Nothing:
println("No user found")
Nothing
A singleton that represents the absence of a value (replaces None):
from koruspy import Nothing, println
empty_result = Nothing
println(empty_result) # Output: Nothing
# Safe operations
def divide(a, b):
if b == 0:
return Nothing
return Some(a / b)
result = divide(10, 0)
println(result) # Output: Nothing (no exception!)
AsyncOption(future)
Wraps asynchronous operations in a type-safe Option:
import asyncio
from koruspy import AsyncOption, println
async def fetch_data():
await asyncio.sleep(0.1)
return "Data loaded"
async def main():
future = fetch_data()
async_result = AsyncOption(future)
# The AsyncOption displays in vibrant purple (OLED-optimized)
println(async_result)
# Await the result
final_result = await async_result.resolve()
println(final_result) # Output: Some(Data loaded)
asyncio.run(main())
⚡ Native Cython Engine (v0.6.1+)
Performance Breakthrough
Starting from version 0.6.1, koruspy implements its core functions in Cython, leveraging C's libc and fflush(stdout) for maximum I/O performance.
Real Mobile Benchmarks:
- Pure Python: 0.017s
- Cython Native: 0.006s
- Performance Gain: ~3x faster
println - Native Output Function
The println function is compiled to native C code, providing blazing-fast output operations:
from koruspy import println, Some, Nothing
# Fast native printing
println("Hello from Cython!")
println(Some(123))
println(Nothing)
# Benchmark comparison
import time
start = time.time()
for i in range(1000):
println(f"Iteration {i}")
end = time.time()
print(f"Execution time: {end - start:.3f}s")
# Mobile result: ~0.006s (vs 0.017s in pure Python)
🔧 Smart Compilation with setup_native()
No external build scripts needed! The setup_native() function compiles all .pyx Cython files directly in the user's environment.
How It Works
import koruspy
# Call once at the start of your application
# This will:
# 1. Detect all .pyx files in koruspy
# 2. Compile them to native extensions (.so or .pyd)
# 3. Make them available for import
koruspy.setup_native()
# Now you can use the high-performance functions
from koruspy import println, Some
When to Use
- First Run: Always call
setup_native()after installation - Updates: Re-run after updating koruspy to recompile extensions
- Deployment: Include in your app initialization for mobile environments
# Example: Mobile app initialization
def initialize_app():
import koruspy
koruspy.setup_native()
from koruspy import println
println("App initialized with native performance!")
initialize_app()
👁️ Accessibility & Visual Health
OLED-Optimized Color System
koruspy uses carefully selected ANSI colors to enhance readability and reduce eye strain on mobile OLED displays:
- 🟢 Green (Some): High contrast, easy to read
- 🔴 Red (Nothing): Clear indication of absence
- 🟣 Vibrant Purple (AsyncOption): Specially chosen to reduce halo/blur effects for developers with astigmatism
Why Purple for AsyncOption?
Developers with astigmatism often experience "halo" or "blur" effects around bright whites and blues on OLED screens. The vibrant purple (#BB86FC) provides:
- Reduced ghosting on dark backgrounds
- High contrast without excessive brightness
- Better focus for astigmatic vision patterns
- Comfortable long-term viewing experience
from koruspy import AsyncOption, println
import asyncio
async def demo():
future = asyncio.sleep(0.1, result="test")
async_opt = AsyncOption(future)
# Purple output is easier on the eyes during development
println(async_opt) # Displays in OLED-friendly purple
asyncio.run(demo())
💡 Use Cases
koruspy excels in scenarios requiring both functional programming patterns and high performance:
API Response Handling
from koruspy import Some, Nothing, println
def fetch_user(user_id):
# Simulate API call
if user_id > 0:
return Some({"id": user_id, "name": "User"})
return Nothing
result = fetch_user(42)
match result:
case Some(user):
println(f"Found user: {user['name']}")
case Nothing:
println("User not found")
Data Pipeline Processing
from koruspy import Some, Nothing, println
def process_data(data):
return (Some(data)
.map(lambda x: x.strip())
.filter(lambda x: len(x) > 0)
.map(lambda x: x.upper()))
result = process_data(" hello ")
println(result) # Output: Some(HELLO)
Async Operations in Mobile Apps
from koruspy import AsyncOption, println
import asyncio
async def load_config():
await asyncio.sleep(0.1) # Simulate network delay
return {"theme": "dark", "lang": "en"}
async def main():
config_future = load_config()
config_option = AsyncOption(config_future)
println("Loading configuration...")
println(config_option) # Purple indicator for async operation
config = await config_option.resolve()
println(config)
asyncio.run(main())
📊 Performance Tips
- Always compile native extensions: Call
setup_native()for maximum speed - Batch operations: Use list comprehensions with Option types for efficiency
- Async for I/O: Leverage
AsyncOptionfor network/disk operations - Mobile optimization: The native engine is specifically tuned for ARM processors
🛠️ Requirements
- Python 3.8+
- Cython (automatically installed)
- C compiler (gcc/clang on Linux/Mac, MSVC on Windows)
📝 License
MIT License - Feel free to use in commercial and open-source projects.
📖 Documentação em Português
🎯 Visão Geral
koruspy é uma biblioteca de lógica funcional projetada para alta performance em ambientes com recursos limitados, especialmente dispositivos móveis e SmartIDE. Construída com aceleração Cython em seu núcleo, a koruspy fornece tipos Option robustos e otimizações de performance nativa que entregam até 3x mais velocidade comparado a implementações Python puras.
✨ Características Principais
- 🔥 Motor Nativo Cython - Funções principais compiladas em C para máxima velocidade
- 📦 Tipos Option Type-Safe -
Some(value),NothingeAsyncOption(future) - ⚡ Ganho de 3x em Performance - Benchmarks reais em mobile: 0.017s → 0.006s
- 🔧 Compilação Zero-Config -
setup_native()integrado para compilação local sem complicação - 👁️ Design com Foco em Acessibilidade - Cores ANSI otimizadas para displays OLED e astigmatismo
- 📱 Otimizado para Mobile - Especialmente ajustado para SmartIDE e ambientes Python móveis
🚀 Início Rápido
Instalação
pip install koruspy
Configuração Básica com Compilação Nativa
import koruspy
# Compila as extensões nativas automaticamente no seu ambiente
koruspy.setup_native()
from koruspy import Some, Nothing, println
# Seu código de alta performance aqui
resultado = Some(42)
println(resultado)
📦 Módulo Option
📊 Módulo de Coleções: SomeList (v0.7.0)
A SomeList é uma implementação de lista à prova de falhas, herdando de MutableSequence. Projetada para processar dados sem interrupções.
- Normalização Automática: Aceita listas, tuplas, sets, geradores ou valores únicos e os normaliza internamente.
- Encadeamento de Métodos:
.append(),.extend()e.insert()retornamself. - Mapeamento Seguro:
.map(fn)retornanothingse a função falhar, protegendo a execução.
from koruspy import SomeList
# Operações funcionais seguras
lista = SomeList([1, 2, None]).filter_nothing()
print(lista.head()) # Output: Some(1)
O tipo Option fornece uma maneira type-safe de lidar com valores opcionais, eliminando erros relacionados ao None.
Some(value)
Representa um valor que existe:
from koruspy import Some, println
nome_usuario = Some("Alice")
println(nome_usuario) # Saída: Some(Alice)
# Pattern matching
match nome_usuario:
case Some(nome):
println(f"Olá, {nome}!")
case Nothing:
println("Usuário não encontrado")
Nothing
Um singleton que representa a ausência de um valor (substitui o None):
from koruspy import Nothing, println
resultado_vazio = Nothing
println(resultado_vazio) # Saída: Nothing
# Operações seguras
def dividir(a, b):
if b == 0:
return Nothing
return Some(a / b)
resultado = dividir(10, 0)
println(resultado) # Saída: Nothing (sem exceção!)
AsyncOption(future)
Envolve operações assíncronas em um Option type-safe:
import asyncio
from koruspy import AsyncOption, println
async def buscar_dados():
await asyncio.sleep(0.1)
return "Dados carregados"
async def main():
future = buscar_dados()
resultado_async = AsyncOption(future)
# O AsyncOption é exibido em roxo vibrante (otimizado para OLED)
println(resultado_async)
# Aguarda o resultado
resultado_final = await resultado_async.resolve()
println(resultado_final) # Saída: Some(Dados carregados)
asyncio.run(main())
⚡ Motor Nativo Cython (v0.6.1+)
Avanço em Performance
A partir da versão 0.6.1, a koruspy implementa suas funções principais em Cython, aproveitando a libc do C e fflush(stdout) para máxima performance de I/O.
Benchmarks Reais em Mobile:
- Python Puro: 0.017s
- Cython Nativo: 0.006s
- Ganho de Performance: ~3x mais rápido
println - Função de Saída Nativa
A função println é compilada para código C nativo, fornecendo operações de saída extremamente rápidas:
from koruspy import println, Some, Nothing
# Impressão nativa rápida
println("Olá do Cython!")
println(Some(123))
println(Nothing)
# Comparação de benchmark
import time
inicio = time.time()
for i in range(1000):
println(f"Iteração {i}")
fim = time.time()
print(f"Tempo de execução: {fim - inicio:.3f}s")
# Resultado mobile: ~0.006s (vs 0.017s em Python puro)
🔧 Compilação Inteligente com setup_native()
Sem necessidade de scripts de build externos! A função setup_native() compila todos os arquivos .pyx Cython diretamente no ambiente do usuário.
Como Funciona
import koruspy
# Chame uma vez no início da sua aplicação
# Isso irá:
# 1. Detectar todos os arquivos .pyx na koruspy
# 2. Compilá-los para extensões nativas (.so ou .pyd)
# 3. Disponibilizá-los para importação
koruspy.setup_native()
# Agora você pode usar as funções de alta performance
from koruspy import println, Some
Quando Usar
- Primeira Execução: Sempre chame
setup_native()após a instalação - Atualizações: Execute novamente após atualizar a koruspy para recompilar as extensões
- Deploy: Inclua na inicialização do seu app para ambientes móveis
# Exemplo: Inicialização de app mobile
def inicializar_app():
import koruspy
koruspy.setup_native()
from koruspy import println
println("App inicializado com performance nativa!")
inicializar_app()
👁️ Acessibilidade e Saúde Visual
Sistema de Cores Otimizado para OLED
A koruspy usa cores ANSI cuidadosamente selecionadas para melhorar a legibilidade e reduzir fadiga visual em displays OLED móveis:
- 🟢 Verde (Some): Alto contraste, fácil de ler
- 🔴 Vermelho (Nothing): Indicação clara de ausência
- 🟣 Roxo Vibrante (AsyncOption): Especialmente escolhido para reduzir efeitos de halo/borrão para desenvolvedores com astigmatismo
Por Que Roxo para AsyncOption?
Desenvolvedores com astigmatismo frequentemente experimentam efeitos de "halo" ou "borrão" ao redor de brancos e azuis brilhantes em telas OLED. O roxo vibrante (#BB86FC) proporciona:
- Redução de ghosting em fundos escuros
- Alto contraste sem brilho excessivo
- Melhor foco para padrões de visão astigmática
- Experiência de visualização confortável a longo prazo
from koruspy import AsyncOption, println
import asyncio
async def demo():
future = asyncio.sleep(0.1, result="teste")
async_opt = AsyncOption(future)
# Saída roxa é mais confortável para os olhos durante desenvolvimento
println(async_opt) # Exibe em roxo amigável para OLED
asyncio.run(demo())
💡 Casos de Uso
A koruspy se destaca em cenários que exigem tanto padrões de programação funcional quanto alta performance:
Manipulação de Respostas de API
from koruspy import Some, Nothing, println
def buscar_usuario(user_id):
# Simula chamada de API
if user_id > 0:
return Some({"id": user_id, "name": "Usuário"})
return Nothing
resultado = buscar_usuario(42)
match resultado:
case Some(usuario):
println(f"Usuário encontrado: {usuario['name']}")
case Nothing:
println("Usuário não encontrado")
Processamento de Pipeline de Dados
from koruspy import Some, Nothing, println
def processar_dados(dados):
return (Some(dados)
.map(lambda x: x.strip())
.filter(lambda x: len(x) > 0)
.map(lambda x: x.upper()))
resultado = processar_dados(" olá ")
println(resultado) # Saída: Some(OLÁ)
Operações Assíncronas em Apps Mobile
from koruspy import AsyncOption, println
import asyncio
async def carregar_config():
await asyncio.sleep(0.1) # Simula delay de rede
return {"tema": "escuro", "idioma": "pt"}
async def main():
config_future = carregar_config()
config_option = AsyncOption(config_future)
println("Carregando configuração...")
println(config_option) # Indicador roxo para operação async
config = await config_option.resolve()
println(config)
asyncio.run(main())
📊 Dicas de Performance
- Sempre compile as extensões nativas: Chame
setup_native()para máxima velocidade - Operações em lote: Use list comprehensions com tipos Option para eficiência
- Async para I/O: Aproveite
AsyncOptionpara operações de rede/disco - Otimização mobile: O motor nativo é especificamente ajustado para processadores ARM
🛠️ Requisitos
- Python 3.8+
- Cython (instalado automaticamente)
- Compilador C (gcc/clang no Linux/Mac, MSVC no Windows)
📝 Licença
Licença MIT - Livre para uso em projetos comerciais e open-source.
Made with ❤️ for mobile developers
High performance meets functional elegance
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file koruspy-0.7.0.tar.gz.
File metadata
- Download URL: koruspy-0.7.0.tar.gz
- Upload date:
- Size: 120.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
55cb948acc756190a09f8ae314b7a7ad6f91676dedcb5b2c6d186b4083bf8c5c
|
|
| MD5 |
fa8aaf718a703e5a2ab0de2e34f0a809
|
|
| BLAKE2b-256 |
140bd9ed46038909d62699590620582de08f25c57e2adc2cbd25c8b9eb283810
|
File details
Details for the file koruspy-0.7.0-py3-none-any.whl.
File metadata
- Download URL: koruspy-0.7.0-py3-none-any.whl
- Upload date:
- Size: 116.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d7cc85ec3312eee72ceaef79825a481e017205b63930ab8729593cc2d8513b57
|
|
| MD5 |
672182d07acf2b8a76e8a5fd866b07b1
|
|
| BLAKE2b-256 |
8f35b4b369a852fab433e0c39a3b4a4084e117f231972339b8c7bf5385194da4
|