

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Sum Types
incomplete
2: Union Types
incomplete
3: Enums
incomplete
4: Sum Types
incomplete
5: Match
incomplete
6: Sum Types Practice
incomplete
This lesson's interactive features are locked, please to keep using them
Unfortunately, Python does not support sum types as well as some statically typed languages.
Python doesn't enforce your types before your code runs. That's why we need this line here to raise an Exception if a color is invalid:
def color_to_hex(color: Color) -> str:
if color == Color.GREEN:
return "#00FF00"
elif color == Color.BLUE:
return "#0000FF"
elif color == Color.RED:
return "#FF0000"
# handle the case where the color is invalid
raise Exception("unknown color")
In a language like Rust, which has an exceptionally rich type system, we could write the same thing like this:
fn color_to_hex(color: Color) -> String {
match color {
Color::Green => "#00FF00".to_string(),
Color::Blue => "#0000FF".to_string(),
Color::Red => "#FF0000".to_string(),
}
}
Notice how there isn't any case for an unknown enum variant? That's because the Rust code will fail to compile (a step that happens before the code runs at all) if the types don't line up. The Rust compiler enforces that a Color value can only be one of the defined variants, and the match color block is required to handle every variant!
This static enforcement is a huge benefit of sum types. It's a shame we can't get that in Python.