Uma biblioteca inspirada em Rust e Kotlin para lidar com Option, println colorido e utilitários.
Project description
🦀 Koruspy 0.3.4 – Atualização
Koruspy é uma biblioteca ultra-leve que traz segurança do Rust e elegância do Kotlin para o Python.
Desenvolvida totalmente via Termux, ela elimina a necessidade de verificações manuais de None e blocos repetitivos try/except, usando Pattern Matching (Python 3.10+) e programação funcional.
🆕 Novidades
to_floatretornanothingem caso de falha, mantendo consistência do singleton_NoneOption.- Novos testes para reforçar a robustez:
- Conversão inválida com
to_float. Some.maplidando comNone.Filterlidando com funções que levantam exceções.Result.mapcaptura exceções e retornaErr.
- Conversão inválida com
🛠️ Correções / Ajustes
Filteragora retornanothingde forma segura, sem propagar exceções.Result.mapcaptura erros e retornaErrsem quebrar o fluxo.- Garantida compatibilidade com pytest e identidade do singleton
nothing.
✅ Testes
- Todos os 26 testes passam, cobrindo:
Some,nothing,Okay,Err,map,Filter,unwrap_or,to_floate integração com generators. - Casos de sucesso, falha e edge cases validados.
🚀 Diferenciais
- Zero NoneErrors: use
Option(Someounothing) para lidar com valores ausentes. - Result Pattern: trate sucessos e falhas como dados, não exceções.
- Estilo Kotlin: métodos encadeáveis como
.map(),.Filter(),.and_then(),.getattr(). - Pipeline seguro:
option_oftrata corretamenteNoneenothing, preservando valores falsy (0,False). - Fallback elegante:
.unwrap_or(default)e.unwrap_or_else(func). - Finalização clara:
.finalize()encerra pipelines com valor garantido. - Terminal colorido: substitua
printporprintln, com suporte a tipos e cores ANSI.
📦 Instalação
Modo editável (Termux ou ambiente mobile):
pip install -e .
📝 exemplos
option_of()
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()
Some("3.14").to_float() # Some(3.14)
Some("abc").to_float() # nothing
nothing.to_float() # nothing
Pipeline com .Filter e ```.finalize``
idade_valida = (
option_of(idade2, 0)
.get_value() # mantém dentro do Option
.Filter(lambda x: x >= 18) # F maiúsculo
.on_nothing(lambda: println("valor inválido"))
.finalize() # sai do pipeline
)
println(idade_valida)
Fallbacks
val = option_of(None, nothing).unwrap_or(42)
println(val) # 42
val2 = option_of(None, nothing).unwrap_or_else(lambda: 99)
println(val2) # 99
get_value() em Loops
from koruspy import option_of, println
arquivos = ["config.yaml", "", None, "dados.json"]
for nome in arquivos:
resultado = (
option_of(nome, "") # default obrigatório
.get_value() # mantém Option
.Filter(lambda x: x.endswith((".yaml", ".json")))
.map(lambda x: x.upper())
.unwrap_or("IGNORADO") # fallback
)
println(resultado)
Dica: use get_value() para permanecer no fluxo Option. Use finalize() para obter o valor cru e sair do pipeline.
English-version 🇺🇸🇬🇧
🦀 Koruspy 0.3.4 – Update
Koruspy is an ultra-lightweight library bringing Rust safety and Kotlin elegance to Python. Eliminates repetitive None checks and try/except blocks via Pattern Matching (Python 3.10+) and functional programming.
🆕 New Features
to_float now returns nothing on failure, ensuring singleton _NoneOption consistency.
Additional tests added to reinforce library robustness:
Invalid conversion with to_float.
Some.map handling None.
Filter handling functions that raise exceptions.
Result.map captures exceptions and returns Err.
🛠️ Fixes / Adjustments
Filter keeps safe behavior, returning nothing instead of propagating exceptions.
Result.map captures errors and returns Err instead of breaking the flow.
Adjustments to ensure pytest compatibility and singleton nothing identity.
✅ Tests
All 26 current tests passed, covering: Some, nothing, Okay, Err, map, Filter, unwrap_or, to_float and generator integration.
Includes validation of success cases, failure cases, and edge cases.
🚀 Highlights
Zero NoneErrors: use Option (Some or nothing) to safely handle missing values.
Result Pattern: handle success/failure as data, not exceptions.
Kotlin-style API: chainable methods like .map(), .Filter(), .and_then(), .getattr().
Safe pipeline: option_of correctly handles None and nothing, preserving falsy values (0, False).
Elegant fallbacks: .unwrap_or(default) and .unwrap_or_else(func).
Clear finalization: .finalize() terminates pipelines with guaranteed values.
Colored terminal output: replace print with println, with type-aware ANSI colors.
📦 Installation
Editable mode (Termux or mobile environment):
pip install -e .
📝 Examples
option_of with default
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
Some("3.14").to_float() # Some(3.14)
Some("abc").to_float() # nothing
nothing.to_float() # nothing
Pipeline with Filter and finalize
valid_age = (
option_of(age2, 0)
.get_value() # stays in Option flow
.Filter(lambda x: x >= 18) # F uppercase
.on_nothing(lambda: println("invalid value"))
.finalize() # exits pipeline
)
println(valid_age)
Fallbacks
val = option_of(None, 42).unwrap_or(42)
println(val) # 42
val2 = option_of(None, 99).unwrap_or_else(lambda: 99)
println(val2) # 99
get_value() in loops
from koruspy import option_of, println
files = ["config.yaml", "", None, "dados.json"]
for name in files:
result = (
option_of(name, "") # default required
.get_value() # stays in Option
.Filter(lambda x: x.endswith((".yaml", ".json")))
.map(lambda x: x.upper())
.unwrap_or("IGNORED") # fallback
)
println(result)
Tip: use get_value() to stay in the Option pipeline. Use finalize() to exit the pipeline and retrieve 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.4.tar.gz.
File metadata
- Download URL: koruspy-0.3.4.tar.gz
- Upload date:
- Size: 5.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
890634066bccde32cc821110124e03c6042ca4fd71d97c61bbc45b0e0b27ef66
|
|
| MD5 |
93313b79cd5bd43bef4aae1cc96c768d
|
|
| BLAKE2b-256 |
d691fb9768a027e929e055a9a584d71ceb6d1f9bd7121d53a248d30ad9a0c6ac
|
File details
Details for the file koruspy-0.3.4-py3-none-any.whl.
File metadata
- Download URL: koruspy-0.3.4-py3-none-any.whl
- Upload date:
- Size: 6.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-requests/2.32.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
414e06ef5a3fd56f4ca468b79a964174272853a1afd90fda46c4a30e496fb958
|
|
| MD5 |
e7b66e4bd2f22f209d87b2b7bde26a3f
|
|
| BLAKE2b-256 |
2e2d3ca892f55c8260ed18710cf70edd967e6fc579d9807c65241c48e46f9a2f
|