Skip to content

Use any and all to make collection non-optional #4573

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 Feb 14, 2018 · 5 comments
Closed

Use any and all to make collection non-optional #4573

ilevkivskyi opened this issue Feb 14, 2018 · 5 comments

Comments

@ilevkivskyi
Copy link
Member

ilevkivskyi commented Feb 14, 2018

I have seen patterns like this several times:

def func() -> Optional[int]:
    pass

def test() -> List[int]:
    vals: Iterable[Optional[int]] = [func() for _ in some_list]
    if all(vals):
        return list(vals)  # None can't be in 'vals' here.
    return []

It would be convenient if binder could understand this for covariant collections.

@gvanrossum
Copy link
Member

gvanrossum commented Feb 14, 2018 via email

@ilevkivskyi
Copy link
Member Author

but we'd have to be sure we are okay with the
refined type of vals not being a subtype of its original type (because of
List invariance).

I think we should only allow narrowing if the original variable is annotated with something like Iterable, Sequence or Container. Invariant containers like List or Dict should stay as is (I think there is already somer code in binder that applies a restriction only if it is a subtype).

@gvanrossum
Copy link
Member

Then your example won't work as written.

Also, I have a vague sense of "déjà vu" about this.

@ilevkivskyi
Copy link
Member Author

ilevkivskyi commented Feb 14, 2018

Then your example won't work as written.

OK, I will updated it.

Also, I have a vague sense of "déjà vu" about this.

Because I proposed and implemented a similar feature for if None not in some_container.

@msullivan
Copy link
Collaborator

I think if we only do this for covariant containers then it feels pretty niche and if we do it for invariant containers then it has problems, so I'm going to close this, but if somebody disagrees with me feel free to reopen

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

No branches or pull requests

4 participants