Uma biblioteca inspirada em Rust e Kotlin para lidar com Option, println colorido e utilitários.
Project description
Koruspy 0.3.3 – Atualização
🆕 Novidades
to_floatagora retornanothingem caso de falha, garantindo consistência do singleton_NoneOption.- Testes extras adicionados para reforçar a robustez da biblioteca:
- Conversão inválida com
to_float. mapdoSomelidando comNone.Filterlidando com funções que levantam exceções.Result.mapcaptura exceções e retornaErr.
- Conversão inválida com
🛠️ Correções / Ajustes
Filtermantém comportamento seguro, retornandonothingem vez de propagar exceções.Result.mapcaptura erros e retornaErrao invés de quebrar o fluxo.- Ajustes para garantir compatibilidade com pytest e identidade do singleton
nothing.
✅ Testes
- Todos os 26 testes atuais passaram, cobrindo
Some,nothing,Okay,Err,map,Filter,unwrap_or,to_floate integração com generators. - Inclui validação de casos de sucesso, falha e edge cases.
Koruspy 0.3.3 – Update
🆕 New Features
to_floatnow returnsnothingon failure, ensuring singleton_NoneOptionconsistency.- Additional tests added to reinforce library robustness:
- Invalid conversion with
to_float. Some.maphandlingNone.Filterhandling functions that raise exceptions.Result.mapcaptures exceptions and returnsErr.
- Invalid conversion with
🛠️ Fixes / Adjustments
Filterkeeps safe behavior, returningnothinginstead of propagating exceptions.Result.mapcaptures errors and returnsErrinstead of breaking the flow.- Adjustments to ensure pytest compatibility and singleton
nothingidentity.
✅ Tests
- All 26 current tests passed, covering
Some,nothing,Okay,Err,map,Filter,unwrap_or,to_floatand generator integration. - Includes validation of success cases, failure cases, and edge cases.
🦀 Koruspy
Koruspy é uma biblioteca ultra-leve que traz a segurança do Rust e a elegância do Kotlin para o ecossistema Python.
Desenvolvida inteiramente via Termux, esta biblioteca elimina a necessidade de verificações manuais de None e blocos try/except repetitivos, utilizando o poder do Pattern Matching (Python 3.10+) e programação funcional.
🚀 Diferenciais
Zero NoneErrors: Use Option (Some ou nothing) para lidar com valores ausentes.
Result Pattern: Trate sucessos e falhas como dados, não como exceções que quebram o código.
Estilo Kotlin: Métodos encadeáveis como .map(), .Filter(), .and_then() e o operador de navegação segura .getattr().
Pipeline seguro: option_of agora trata corretamente None e nothing, preservando valores falsy como 0 e False.
Finalização clara: .finalize() encerra pipelines que já têm valor garantido.
Fallback elegante: .unwrap_or(default) e .unwrap_or_else(func) fornecem valores quando necessário.
Terminal Colorido: Substitua o print padrão pelo println com suporte a tipos e cores ANSI.
📦 Instalação
Como você está desenvolvendo no Termux ou em ambiente mobile, instale via modo editável:
pip install -e .
📝 Exemplos:
option_of trata None e nothing, preservando falsy
from koruspy import Some, nothing, option_of, println
idade = option_of(0, 18)
println(idade) # Some(0)
idade2 = option_of(None, 18)
println(idade2) # Some(18)
to_float
Converte o valor contido em Some para float de forma segura.
- Retorna
Some(float)se a conversão for bem-sucedida. - Retorna
NoneOptioncaso a conversão falhe. - Em
NoneOption, o método retorna a própria instância.
Exemplo:
Some("3.14").to_float() # Some(3.14)
Some("abc").to_float() # NoneOption
NoneOption.to_float() # NoneOption
Pipeline com Filter e finalize
idade_valida = (
option_of(idade2, 0)
.get_value()
.Filter(lambda x: x >= 18)
.on_nothing(lambda: println("valor inválido"))
.finalize()
)
println(idade_valida)
Fallbacks
val = option_of(None).unwrap_or(42)
println(val) # 42
val2 = option_of(None).unwrap_or_else(lambda: 99)
println(val2) # 99
função get_value():
from koruspy import option_of
arquivos = ["config.yaml", "", None, "dados.json"]
for nome in arquivos:
opt = option_of(nome)
resultado = (
opt
.get_value() # 👈 retorna Option
.Filter(lambda x: x.endswith((".yaml", ".json")))
.map(lambda x: x.upper())
)
print(resultado)
Regra de ouro: Use
get_value()para permanecer dentro do pipelineOption. Usefinalize()para sair do pipeline e obter o valor crua.
English Version 🇺🇸🇬🇧:
🦀 Koruspy
Koruspy is an ultra-lightweight library that brings Rust’s safety and Kotlin’s elegance to the Python ecosystem.
Developed entirely via Termux, this library removes the need for manual None checks and repetitive try/except blocks by leveraging the power of Pattern Matching (Python 3.10+) and functional programming.
🚀 Highlights
Zero NoneErrors: Use Option (Some or nothing) to safely handle missing values.
Result Pattern: Handle success and failure as data, not as exceptions that break control flow.
Kotlin-style API: Chainable methods like .map(), .Filter(), .and_then(), and the safe navigation operator .getattr().
Safe pipeline: option_of now correctly handles None and nothing, while preserving falsy values such as 0 and False.
Clear finalization: .finalize() terminates pipelines when a value is guaranteed.
Elegant fallbacks: .unwrap_or(default) and .unwrap_or_else(func) provide values when needed.
Colored terminal output: Replace the standard print with println, with type-aware ANSI color support.
📦 Installation
If you are developing on Termux or in a mobile environment, install using editable mode:
pip install -e .
📝 Examples:
option_of handles None and nothing, preserving falsy values
from koruspy import Some, nothing, option_of, println
age = option_of(0, 18)
println(age) # Some(0)
age2 = option_of(None, 18)
println(age2) # Some(18)
to_float
Safely converts the value contained in Some to float.
- Returns
Some(float)if the conversion succeeds. - Returns
NoneOptionif the conversion fails. - When called on
NoneOption, the method returns itself.
Example:
Some("3.14").to_float() # Some(3.14)
Some("abc").to_float() # NoneOption
NoneOption.to_float() # NoneOption
Pipeline with Filter and finalize
valid_age = (
option_of(age2, 0)
.get_value()
.Filter(lambda x: x >= 18)
.on_nothing(lambda: println("invalid value"))
.finalize()
)
println(valid_age)
Fallbacks
val = option_of(None).unwrap_or(42)
println(val) # 42
val2 = option_of(None).unwrap_or_else(lambda: 99)
println(val2) # 99
function get_value():
from koruspy import option_of
user_inputs = ["42", "", None, "abc"]
for value in user_inputs:
result = (
option_of(value)
.get_value() # 👈 returns a new Option
.map(int)
.Filter(lambda x: x > 0)
)
print(result)
Rule of thumb: Use
get_value()to stay inside the Option pipeline. Usefinalize()to exit the pipeline and retrieve the raw value.
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.3.3.tar.gz.
File metadata
- Download URL: koruspy-0.3.3.tar.gz
- Upload date:
- Size: 5.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fbbc1f32256619f10de83dc6fa0d65892b6ba9eab8fc1360b2ba0f264b88bdea
|
|
| MD5 |
b37f70611749751750fa1a82212a8c5d
|
|
| BLAKE2b-256 |
4a854d9a4e89729c59b090e5714bc0441d414cb55a64a0b31ad558817eee3ea7
|
File details
Details for the file koruspy-0.3.3-py3-none-any.whl.
File metadata
- Download URL: koruspy-0.3.3-py3-none-any.whl
- Upload date:
- Size: 6.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
561f47a527bef74cae2d8e482488cbcfa4849e76466e96e3d2856828ef7821e7
|
|
| MD5 |
2fbc7d084bcffa4d5ece35b2aaa89a09
|
|
| BLAKE2b-256 |
899c420b0f0e73f74bceecaff3144117d7a7de0a3ea31a350d07f2d3bd437859
|