Skip to content
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

Variant of safe that preserves the argument that lead to an exception #264

Closed
stereobutter opened this issue Feb 15, 2020 · 8 comments · Fixed by #1217
Closed

Variant of safe that preserves the argument that lead to an exception #264

stereobutter opened this issue Feb 15, 2020 · 8 comments · Fixed by #1217
Assignees
Labels
enhancement New feature or request

Comments

@stereobutter
Copy link

I propose a function/decorator (maybe attempt would be a good name?) similar to safe with the twist of returning Failure(bad_input) from safe(f)(bad_input) instead of Failure(SomeException). An example where this would be useful:

(
    attempt(json.loads)('<hello world>')
    .alt(lambda s: ValueError(f'"{s}" is not a valid json')) 
)
# Failure(ValueError('"<hello world>" is not a valid json'))
@sobolevn
Copy link
Member

Oh, I see. Do you want to send a PR?

@sobolevn sobolevn added the enhancement New feature or request label Feb 15, 2020
@stereobutter
Copy link
Author

I haven't worked with mypy plugins/decorators in a while so I'm not sure if there is a neat way to implement attempt (in a typesafe way) leveraging the existing implementation of safe? Of course one could just copy past the implementation for safe and its plugin but that is imho not a very nice solution. What do you think?

@sobolevn
Copy link
Member

It can be a good be a start.

@stereobutter
Copy link
Author

After looking into this for the last half hour I think getting this to typecheck without something like https://www.python.org/dev/peps/pep-0612/ will require its own plugin since one has to get at the types of the arguments of f in attempt(f). :(

@sobolevn
Copy link
Member

I think so too, that's the big problem with mypy.

@thepabloaguilar
Copy link
Member

I was thinking about the implementation here, one thing we need to define is what to do with functions that has multiple parameters, like, if my function has 3 arguments like:

def my_func(a, b, *, c):
    pass

my_func(1, 2, c=3)

What should be inside the Result? A tuple where the first element is the positional args and then the second the keyword args?

@thepabloaguilar
Copy link
Member

Any thoughts @sobolevn??

@sobolevn
Copy link
Member

sobolevn commented Jan 6, 2022

I think that functions with multiple arguments should not be allowed in this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Development

Successfully merging a pull request may close this issue.

3 participants