radix / sumtypes

Sum Types, aka Tagged Unions, for Python
MIT License
42 stars 1 forks source link

SumTypes of non-trivial classes? #5

Closed asmodehn closed 4 years ago

asmodehn commented 5 years ago

Hi,

I am discovering this lib, trying to model behaviour in python in a bit cleaner way than what is usually done... So I was trying to get sumtypes to work on classes that I already defined and use independently of in other parts of the code. However I couldn't find any documentation about that...

The constructor doesn't let the user specify how to build the instance ? I notice I can use attrs, but what about dataclasses ? What about having a union between this non-trivial typeA and that non-trivial typeB ?

Thanks for any help !

radix commented 4 years ago

In order to have a tagged union of existing types, you should just create a sum type that wraps those existing types, like:

@sumtype
class MyType(object):
    # constructors specify names for their arguments
    MyExistingType = constructor('value')
    MyOtherExistingType = constructor('value')

and wrap your existing values with x = MyType.MyExistingType(value_of_my_existing_type). this will then allow you to pattern match on x to determine the type of the inner value.