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, Scalar_Variant, Struct_Variant
@Enum
class Color:
Red: Scalar_Variant
Blue: Scalar_Variant
Green: Scalar_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.4.tar.gz
(3.8 kB
view details)
Built Distribution
File details
Details for the file ricetypes-0.1.4.tar.gz
.
File metadata
- Download URL: ricetypes-0.1.4.tar.gz
- Upload date:
- Size: 3.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.0 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4ab8a1b8a16c3b064af0ee8430a75177d38e7f0cccbd4c1eef0bc368c94c2a4b |
|
MD5 | 5c9c4f4a77e0db191ebcf085b85701c8 |
|
BLAKE2b-256 | 30de93bf82179cbfa0c466cd5092ba0fde20fdf029e6065b2e7cb24372503aeb |
File details
Details for the file ricetypes-0.1.4-py3-none-any.whl
.
File metadata
- Download URL: ricetypes-0.1.4-py3-none-any.whl
- Upload date:
- Size: 3.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.0 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 163ee427de565af15f744b78064465d7fa92dce5ceafeb2004e7ceecb213a88f |
|
MD5 | a688a582b4c7b512623ac5b1a8081659 |
|
BLAKE2b-256 | 2daa70d8b5391c2be0725e21f4df4ad4b5a8d20bc2042668787c316d3ffe95de |