Skip to main content

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

Python Cython Mobile License

Functional programming patterns optimized for mobile environments and SmartIDE

English | Português


📖 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, and AsyncOption(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.

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

  1. Always compile native extensions: Call setup_native() for maximum speed
  2. Batch operations: Use list comprehensions with Option types for efficiency
  3. Async for I/O: Leverage AsyncOption for network/disk operations
  4. 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), Nothing e AsyncOption(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

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

  1. Sempre compile as extensões nativas: Chame setup_native() para máxima velocidade
  2. Operações em lote: Use list comprehensions com tipos Option para eficiência
  3. Async para I/O: Aproveite AsyncOption para operações de rede/disco
  4. 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


Download files

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

Source Distribution

koruspy-0.6.2.tar.gz (117.9 kB view details)

Uploaded Source

Built Distribution

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

koruspy-0.6.2-py3-none-any.whl (114.5 kB view details)

Uploaded Python 3

File details

Details for the file koruspy-0.6.2.tar.gz.

File metadata

  • Download URL: koruspy-0.6.2.tar.gz
  • Upload date:
  • Size: 117.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.32.5

File hashes

Hashes for koruspy-0.6.2.tar.gz
Algorithm Hash digest
SHA256 7a890f1cda414b15d5f9eb515f5a066c5ae2179035f9b7b65146b37e3ac3cd93
MD5 6ea87429e191a9356b4ea33418b24e94
BLAKE2b-256 da4d85339dbb8fce69698cbef7de04b03a603397f9c4cb9825c30fd26631aae6

See more details on using hashes here.

File details

Details for the file koruspy-0.6.2-py3-none-any.whl.

File metadata

  • Download URL: koruspy-0.6.2-py3-none-any.whl
  • Upload date:
  • Size: 114.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.32.5

File hashes

Hashes for koruspy-0.6.2-py3-none-any.whl
Algorithm Hash digest
SHA256 51df600e62f5d3fe9513a08833f19f082fda0ce8998f5ff5c14ce81ade66881a
MD5 e4620002d70647aad7aa9eb73624155d
BLAKE2b-256 fe87c081e722e31bcb2c3aa932e3e1ad78911bacd8b65aa18483a67c4d13d92b

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