Some nice type like things
Project description
ricetypes
This is a little library that defines some nice type constructs that I like to have.
Install
pip install ricetypes
Enums (Discriminated Unions)
I have implemented something approximating rust enums.
from ricetypes import Enum, Scailer_Variant, Struct_Variant
@Enum
class Color:
Red: Scailer_Variant
Blue: Scailer_Variant
Green: Scailer_Variant
RGB: Struct_Variant(int, int, int, alpha=float)
r = Color.Red
b = Color.Blue
g = Color.Green
whilte = Color.RGB(100,100,100, alpha=.1)
print(white.alpha)
print(white._0, white._1, white_2)
print(white.tuple)
print(white.dict)
match r:
case Color.Red:
print('red')
case Color.Blue:
print('blue')
case Color.Green:
print('green')
# unfortunatly you cant use Struct_Variants in a match statment
Result
It includes the Result type:
from ricetypes import Result
r = Result.Ok(10)
from math import sqrt
r.map(sqrt).unwrap()
r = Result.Error('sad').maperr(str.upper)
if r.error:
print(r._error)
try:
r.with_exception(KeyError).unwrap()
except KeyError as e:
print(e)
try:
r.unwrap()
except Exception as e:
print(e)
# We can chain functions together using map
inc = lambda n: n+1
Result.Ok(0).map(inc).map(inc).map(sqrt)
# And we can chain functions that return an Option together using a bind
def foo(x: int, y:int):
if x < y:
return Result.Ok(y)
return Result.Error(f'y must be bigger then x but x={x}, y={y}')
Result.Ok(0).bind(foo, 10).bind(foo,30).bind(foo,20).or_else(-1)
Option
from ricetypes import Option
op = Option.Some('value')
if op.something:
print(op.value)
op.map(str.upper)
op = Option.Nothing
op.or_else('hi')
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
ricetypes-0.1.1.tar.gz
(3.5 kB
view details)
Built Distribution
File details
Details for the file ricetypes-0.1.1.tar.gz
.
File metadata
- Download URL: ricetypes-0.1.1.tar.gz
- Upload date:
- Size: 3.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ef83277f4e8524c33aa47d2ea9acddf5e2e9927eb694c9c0777a264900fe34fd |
|
MD5 | c3b78d21058f239a22bf363d3626b079 |
|
BLAKE2b-256 | 0b0a3cab2f033597aa6bada3c4c4c578c3248f64899cd0f1364d2c1a1037a830 |
File details
Details for the file ricetypes-0.1.1-py3-none-any.whl
.
File metadata
- Download URL: ricetypes-0.1.1-py3-none-any.whl
- Upload date:
- Size: 3.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7a62d8262725cd9886625e8ed6a347d8d99c791cbfdd837d6b3dba9d8ca05723 |
|
MD5 | 64d4dba3abfb8fb2c5b633ba3909661a |
|
BLAKE2b-256 | 505cfc02ff93ff2b9eea4b3a6e7c8fa43ed264f147bac4bd02e82c58881c15c7 |