Skip to content

Add runtime support for optional types #420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ilevkivskyi opened this issue May 1, 2017 · 2 comments
Closed

Add runtime support for optional types #420

ilevkivskyi opened this issue May 1, 2017 · 2 comments
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@ilevkivskyi
Copy link
Member

While working on -strict-optional mode in mypy, I noticed patterns like this many times:

def func(x: Optional[X]) -> Optional[Y]:
    if x is None:
        return None
    # do some stuff with 'x'

The most recent example appeared in python/mypy#3295. I could imagine this pattern (monadic behaviour) is quite common. If one uses "error as value" (i.e. passing None instead of using an exception), then the above pattern is necessary for "piping". Maybe we could provide a decorator that will automatically add such behaviour to a function, schematically:

def maybe(func):
    def inner(*args):
        if None in args:
            return None
        return func(*args)
    return inner

@maybe
def convert_to_str(x):
    return 'converted: ' + str(x)

The decorator is very simple, but the thing it does looks very common.

@srittau srittau added the topic: feature Discussions about new features for Python's type annotations label Nov 4, 2021
@davidfstr
Copy link
Contributor

@ilevkivskyi I'm not convinced this pattern is common enough to put in the typing module. Seems like something you'd put in your own codebase.

@srittau
Copy link
Collaborator

srittau commented Apr 18, 2022

This also looks unrelated to typing, more something I'd expect in functools. I'm closing this here for now.

@srittau srittau closed this as completed Apr 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

3 participants