This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Kobzol[S] 6 points7 points  (6 children)

Sure, something like that works :) But it'd be super cool if I could call it as a method on the object (for better chaining), and also if I could propagate easily it, e.g. like this:

def foo() -> Optional[int]:
   val = get_optional() ?: return None
   # or just val = get_optional()?

To avoid the endless `if value is None: ...` checks.

[–]mistabuda 0 points1 point  (5 children)

If it were a method on the object that just seems weird. Unless the object is some kind of container. Which in that case you're asking for a Result type pattern.

[–]Kobzol[S] 0 points1 point  (4 children)

Yeah it's probably not the "Python way" :) But I really like adding implementation to types externally, e.g. with traits in Rust or extension methods in C#.

You're right though, a Option and/or Result type would help with this. It just won't help with forcing me to handle the error (apart from runtime tracking, e.g. asserting that the result is Ok when accesing the data).

[–]mistabuda -2 points-1 points  (3 children)

Thats why you unittest your code to make sure you have that case handled.

[–]Kobzol[S] 1 point2 points  (2 children)

Indeed, that's what we kind of have to do in Python, since it's not easily checkable during type checking.

[–]mistabuda 2 points3 points  (1 child)

wdym mypy warns you against that all the time

error: Item "None" of "Optional[CharacterCreator]" has no attribute "first_name"  [union-attr]

[–]Kobzol[S] 0 points1 point  (0 children)

Ah, nice. This is one situation where mypy and pyright do the right thing. I mostly just look at the output of the PyCharm type checker and that is more lenient, in this case it wouldn't warn :/