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

[Question] Is it possible to signal a function returns a specific value #2390

Closed
sk- opened this issue Aug 16, 2018 · 4 comments
Closed

[Question] Is it possible to signal a function returns a specific value #2390

sk- opened this issue Aug 16, 2018 · 4 comments

Comments

@sk-
Copy link
Contributor

sk- commented Aug 16, 2018

Hi everyone, I'm trying to add type annotations for a third_party module, namely more_itertools. The function I'm having issues with is first_true, which is defined as

def first_true(iterable, default=False, pred=None): ...

This means that the return type would be either Union[T, bool] or Union[T, U] when there's an explicit default.

The problem is that in the case of an implicit default, the pattern

element = find_true(elements, pred=....)
if element:
  # do something with the element

would not work as inside the if, element could still be True.

What I would like is to signal that the return type is either T or the value False, is there any idiom to do that?

Note that the same is true for builtin functions like next. See
https://github.com/python/typeshed/blob/master/stdlib/3/builtins.pyi#L862

ps: I know this would be solved if the API changed to have default=None instead.

@JelleZijlstra
Copy link
Member

That's not currently supported, but the mypy team is planning to add support for a feature like this ("final types") soon.

@srittau
Copy link
Collaborator

srittau commented Oct 28, 2018

I think the question has been answered.

@srittau srittau closed this as completed Oct 28, 2018
@sk-
Copy link
Contributor Author

sk- commented Oct 28, 2018

@srittau It would be great if you could add a link to the tracking issue for "the mypy team is planning to add support for a feature like this ("final types") soon."

@srittau
Copy link
Collaborator

srittau commented Oct 28, 2018

Dependent types (I think this is what @JelleZijlstra was referring to) are discussed in python/mypy#3062.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants