Skip to content

Support type information from conditional expressions #806

Closed

Description

@mrwright

In code like the following:

from typing import *

x = {1: 2} # type: Union[Dict[int, int], str]
x.get(1, 1) if isinstance(x, dict) else 0

we should be able to figure out that x must be A Dict, but instead we get the error

dict.py:4: error: Some element of union has no attribute "get"

Activity

  1. sametmax commented on Oct 14, 2016

    @sametmax

    If there the same fix with if callable()? Because I got this:

        def __getitem__(self, index):
            # type: (Union[int, slice, Callable]) -> Union[IterableWrapper, Any]
    
            if isinstance(index, int):
                return at_index(self.iterator, index)
    
            if callable(index):
                return first_true(self.iterator, index) 
    
            start = index.start or 0
            step = index.step or 1
            stop = index.stop
    

    And mypy complains that index may not have a start attribute.

  2. rwbarton commented on Oct 14, 2016

    @rwbarton
    Contributor

    I think adding this kind of logic with if callable(x): has come up before in this issue tracker. It should be easy to do (with the provision that mypy currently only understands that Callable things are callable, but not in general instances with __call__ methods; but that should be sufficient in your example).

  3. gvanrossum commented on Oct 14, 2016

    @gvanrossum
    Member

    Yeah, adding callable() is #1973. Better support for __call__ is #797.

    On Fri, Oct 14, 2016 at 5:53 AM, Reid Barton [email protected]
    wrote:

    I think adding this kind of logic with if callable(x): has come up before
    in this issue tracker. It should be easy to do (with the provision that
    mypy currently only understands that Callable things are callable, but
    not in general instances with call methods; but that should be
    sufficient in your example).

    —
    You are receiving this because you are subscribed to this thread.
    Reply to this email directly, view it on GitHub
    #806 (comment), or mute
    the thread
    https://github.com/notifications/unsubscribe-auth/ACwrMq0sBStYWXKaDvREt3fyUIWvdpx8ks5qz3svgaJpZM4Ft1q_
    .

    --Guido van Rossum (python.org/~guido)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions