Uma biblioteca inspirada em Rust e Kotlin para lidar com Option, println colorido e utilitários.
Project description
Documentação do Módulo Option - koruspy v0.6.0
🇧🇷 Versão em Português
Visão Geral
O módulo Option da koruspy é uma estrutura de programação funcional projetada para eliminar o uso de None e fornecer segurança de tipos em operações que podem ou não retornar um valor. Inspirado em linguagens como Rust e Scala, o Option traz robustez para aplicações Python mobile de alta performance.
Arquitetura
O módulo é composto por três classes principais:
1. Some(value)
Representa um valor presente e válido.
from koruspy import Some
resultado = Some(42)
println(resultado) # Saída: Some(42) [em verde]
2. nothing (singleton de _NoneOption)
Representa a ausência de valor de forma segura e tipada. É um singleton global para uso direto.
from koruspy import nothing
resultado = nothing
println(resultado) # Saída: nothing [em cinza]
3. AsyncOption(future)
Encapsula operações assíncronas que retornam Option.
from koruspy import AsyncOption
import asyncio
async def buscar_dados():
await asyncio.sleep(1)
return Some(100)
resultado = AsyncOption(buscar_dados())
println(resultado) # Saída: AsyncOption(...) [em roxo]
🚀 Performance com Cython (v0.6.0)
Motor de Saída println
A versão 0.6.0 introduz o println, um sistema de saída otimizado implementado em Cython que acessa diretamente a libc do C e utiliza fflush(stdout) para garantir máxima eficiência.
Comparação de Performance
| Método | Tempo (10.000 iterações) | Ganho |
|---|---|---|
print() Python nativo |
0.017s | - |
println() Cython |
0.006s | 3x mais rápido |
Ambiente de teste: Dispositivo mobile Android (ARM64), Python 3.11
# Exemplo de benchmark
from koruspy import println, Some
import time
start = time.perf_counter()
for i in range(10000):
println(Some(i))
end = time.perf_counter()
print(f"Tempo total: {end - start:.3f}s")
📦 Instalação e Compilação
Pré-requisitos
- Python 3.8+
- Cython
- Compilador C (GCC/Clang no Linux/Mac, MSVC no Windows)
Instalação via PyPI
pip install koruspy
Compilação Local (Opcional - para máxima performance)
Para ativar o motor de alta performance com Cython, execute o script de build incluído no pacote:
# Após instalar o koruspy
python build_println.py
O script automaticamente:
- Executa
setup.py build_ext --inplace - Move o binário
.so(Linux/Mac) ou.pyd(Windows) paraprintlnUtils/ - Configura o módulo para uso
Verificando a Instalação
from koruspy import println, Some
println(Some("Compilação bem-sucedida!"))
# Se aparecer em verde, o Cython está ativo
♿ Acessibilidade Visual
Sistema de Cores ANSI
O koruspy implementa um esquema de cores otimizado para reduzir fadiga visual em telas pequenas, especialmente útil para desenvolvedores com astigmatismo:
| Tipo | Cor | Código ANSI | Propósito |
|---|---|---|---|
Some |
Verde | \033[32m |
Indica sucesso/valor presente |
nothing |
Cinza | \033[90m |
Indica ausência de valor |
AsyncOption |
Roxo | \033[35m |
Indica operação assíncrona |
Benefícios
- Contraste suave: Evita cores primárias fortes que causam cansaço
- Distinção clara: Facilita identificação rápida do estado
- SmartIDE friendly: Otimizado para editores mobile com telas 5-7"
🎯 Exemplos Práticos
Exemplo 1: Validação de Entrada
from koruspy import Some, nothing, println
def dividir(a: int, b: int):
if b == 0:
return nothing
return Some(a / b)
resultado = dividir(10, 2)
println(resultado) # Some(5.0) [verde]
resultado_erro = dividir(10, 0)
println(resultado_erro) # nothing [cinza]
Exemplo 2: Pipeline Assíncrono
from koruspy import AsyncOption, Some, println
import asyncio
async def buscar_usuario(id: int):
await asyncio.sleep(0.5)
if id > 0:
return Some({"nome": "Alice", "id": id})
return nothing
async def main():
opcao = AsyncOption(buscar_usuario(1))
resultado = await opcao.value
println(resultado) # Some({'nome': 'Alice', 'id': 1})
asyncio.run(main())
Exemplo 3: Encadeamento Seguro
from koruspy import Some, nothing
def processar_dados(option):
return option.map(lambda x: x * 2).filter(lambda x: x > 10)
println(processar_dados(Some(10))) # Some(20)
println(processar_dados(nothing)) # nothing
📚 Comparação com None do Python
| Aspecto | None Python |
koruspy Option |
|---|---|---|
| Segurança de tipos | ❌ Pode causar AttributeError |
✅ Type-safe, evita erros em runtime |
| Composição | ❌ Requer verificações manuais | ✅ map(), filter(), flatMap() |
| Visibilidade | ❌ Sem distinção visual | ✅ Cores ANSI para debugging rápido |
| Performance | ⚡ Nativa | ⚡⚡⚡ 3x mais rápida com Cython |
| Async-friendly | ❌ Requer wrappers manuais | ✅ AsyncOption nativo |
🔧 Troubleshooting
Problema: "Cores não aparecem no terminal"
Solução: Verifique se seu terminal suporta ANSI. No Windows, use Windows Terminal ou ative o suporte:
import os
os.system('color') # Ativa ANSI no Windows
Problema: "println não está mais rápido"
Solução: Verifique se a extensão Cython foi compilada:
ls printlnUtils/*.so # Linux/Mac
dir printlnUtils\*.pyd # Windows
Se não existir, recompile com python build_println.py.
🤝 Contribuindo
O koruspy é um projeto desenvolvido com foco em acessibilidade mobile! Se você tem sugestões, melhorias ou encontrou bugs, entre em contato com o desenvolvedor.
Desenvolvido para celular, por desenvolvedores mobile.
📄 Sobre o Projeto
koruspy é uma biblioteca focada em performance e acessibilidade para desenvolvimento Python mobile, parte do ecossistema SmartIDE.
🇺🇸 English Version
Overview
The Option module in koruspy is a functional programming structure designed to eliminate the use of None and provide type safety for operations that may or may not return a value. Inspired by languages like Rust and Scala, Option brings robustness to high-performance mobile Python applications.
Architecture
The module consists of three main classes:
1. Some(value)
Represents a present and valid value.
from koruspy import Some
result = Some(42)
println(result) # Output: Some(42) [in green]
2. nothing (singleton of _NoneOption)
Represents the absence of a value in a safe and typed manner. It's a global singleton for direct use.
from koruspy import nothing
result = nothing
println(result) # Output: nothing [in gray]
3. AsyncOption(future)
Encapsulates asynchronous operations that return Option.
from koruspy import AsyncOption
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return Some(100)
result = AsyncOption(fetch_data())
println(result) # Output: AsyncOption(...) [in purple]
🚀 Performance with Cython (v0.6.0)
println Output Engine
Version 0.6.0 introduces println, an optimized output system implemented in Cython that directly accesses C's libc and uses fflush(stdout) to ensure maximum efficiency.
Performance Comparison
| Method | Time (10,000 iterations) | Gain |
|---|---|---|
Python native print() |
0.017s | - |
Cython println() |
0.006s | 3x faster |
Test environment: Android mobile device (ARM64), Python 3.11
# Benchmark example
from koruspy import println, Some
import time
start = time.perf_counter()
for i in range(10000):
println(Some(i))
end = time.perf_counter()
print(f"Total time: {end - start:.3f}s")
📦 Installation and Compilation
Prerequisites
- Python 3.8+
- Cython
- C Compiler (GCC/Clang on Linux/Mac, MSVC on Windows)
Installation via PyPI
pip install koruspy
Local Compilation (Optional - for maximum performance)
To activate the high-performance engine with Cython, run the build script included in the package:
# After installing koruspy
python build_println.py
The script automatically:
- Executes
setup.py build_ext --inplace - Moves the
.so(Linux/Mac) or.pyd(Windows) binary toprintlnUtils/ - Configures the module for use
Verifying Installation
from koruspy import println, Some
println(Some("Compilation successful!"))
# If it appears in green, Cython is active
♿ Visual Accessibility
ANSI Color System
koruspy implements an optimized color scheme to reduce visual fatigue on small screens, especially useful for developers with astigmatism:
| Type | Color | ANSI Code | Purpose |
|---|---|---|---|
Some |
Green | \033[32m |
Indicates success/value present |
nothing |
Gray | \033[90m |
Indicates absence of value |
AsyncOption |
Purple | \033[35m |
Indicates asynchronous operation |
Benefits
- Soft contrast: Avoids strong primary colors that cause fatigue
- Clear distinction: Facilitates quick state identification
- SmartIDE friendly: Optimized for mobile editors with 5-7" screens
🎯 Practical Examples
Example 1: Input Validation
from koruspy import Some, nothing, println
def divide(a: int, b: int):
if b == 0:
return nothing
return Some(a / b)
result = divide(10, 2)
println(result) # Some(5.0) [green]
error_result = divide(10, 0)
println(error_result) # nothing [gray]
Example 2: Asynchronous Pipeline
from koruspy import AsyncOption, Some, println
import asyncio
async def fetch_user(id: int):
await asyncio.sleep(0.5)
if id > 0:
return Some({"name": "Alice", "id": id})
return nothing
async def main():
option = AsyncOption(fetch_user(1))
result = await option.value
println(result) # Some({'name': 'Alice', 'id': 1})
asyncio.run(main())
Example 3: Safe Chaining
from koruspy import Some, nothing
def process_data(option):
return option.map(lambda x: x * 2).filter(lambda x: x > 10)
println(process_data(Some(10))) # Some(20)
println(process_data(nothing)) # nothing
📚 Comparison with Python's None
| Aspect | Python None |
koruspy Option |
|---|---|---|
| Type safety | ❌ Can cause AttributeError |
✅ Type-safe, prevents runtime errors |
| Composition | ❌ Requires manual checks | ✅ map(), filter(), flatMap() |
| Visibility | ❌ No visual distinction | ✅ ANSI colors for quick debugging |
| Performance | ⚡ Native | ⚡⚡⚡ 3x faster with Cython |
| Async-friendly | ❌ Requires manual wrappers | ✅ Native AsyncOption |
🔧 Troubleshooting
Issue: "Colors don't appear in terminal"
Solution: Check if your terminal supports ANSI. On Windows, use Windows Terminal or enable support:
import os
os.system('color') # Enables ANSI on Windows
Issue: "println is not faster"
Solution: Verify that the Cython extension was compiled:
ls printlnUtils/*.so # Linux/Mac
dir printlnUtils\*.pyd # Windows
If it doesn't exist, recompile with python build_println.py.
🤝 Contributing
koruspy is a project developed with a focus on mobile accessibility! If you have suggestions, improvements, or found bugs, please contact the developer.
Built for mobile, by mobile developers.
📄 About the Project
koruspy is a library focused on performance and accessibility for mobile Python development.
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.6.1.tar.gz.
File metadata
- Download URL: koruspy-0.6.1.tar.gz
- Upload date:
- Size: 114.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8102b9bf64d7b37f194f7a8fbbba17b9a7d1df22177b2f4cc2c4e6cdd892a865
|
|
| MD5 |
75b7bbd6988c7b02a349ecbc868a79fa
|
|
| BLAKE2b-256 |
3a0fa06ba97dfa3b1cc6ccc2f574459faf76724b7db556284972c9971c33d456
|
File details
Details for the file koruspy-0.6.1-py3-none-any.whl.
File metadata
- Download URL: koruspy-0.6.1-py3-none-any.whl
- Upload date:
- Size: 112.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f072661a4d9e3df53b01945c6ab45578a22f0581fcb2a1847c111d7bcc6e952e
|
|
| MD5 |
ada8eb5ed11a2b6a6d7a35b253df069d
|
|
| BLAKE2b-256 |
551ce9b0a1b32e53ec45ef1da89c56ad048813535daee0e33ba21ae883e6c591
|