4 ms·
Thanks for the clarification though your example is unpythonic. Here's refactored to be more pythonic and I'd argue it's more readable than pattern match altern
by wraptile 6y ago
Thanks for the clarification though your example is unpythonic. Here's refactored to be more pythonic and I'd argue it's more readable than pattern match alternative:
pet = json_pet.get('type')
if pet == 'cat':
return Cat(json_pet['name'], json_pet['pattern'])
if pet == 'dog':
return Dog(json_pet['name'], json_pet['breed'])
Again it goes against the pep20 which is really the philosophical foundation of the language: "There should be one-- and preferably only one --obvious way to do it."
- danohuiginn 6y agoThe difference is the error handling. Suppose the json includes a dog with no breed specified.
- dguaraglia 6y agoAs danohuiginn clarified, the reason I'm adding the checks is because assuming there's such a key as 'breed' in the json_pet dictionary can (and will!) lead to KeyError exceptions.
- wraptile 6y agoSeems like an issue of data flow then. You usually don't work with dynamic random content and sanitize/clean up your data before working with it.
- dguaraglia 6y agoEven if you were using pre-processed data, pattern matching helps to make the code easier to read. I guess I can think of clearer examples in other languages, like Rust, that supported tagged unions: // Given this enum enum NumOrStr { Num(i32), Str(string) } // That allows you to define values like this let x = NumOrStr::Num(10); let y = NumOrStr::Str("hello"); // And some random code that produces a value z that is of type NumOrStr let z: NumOrStr = ... match z { Num(50) => println!("Got my favorite number: fifty!"), Num(n) => println!('Got {}', n), String("hello") => say_hello(), String(s) => do_something_with_string(s) _ => println!("Default case, x = {:?}", x), }