Skip to content

confusing behavior with TypeVars and multiple inheritance checks in 0.770 #8604

Open
@chadrik

Description

@chadrik

Hi, I was just testing out 0.770 and I'm getting a surprising result:

from typing import TypeVar

class Foo(object):
    pass

FooOrStr = TypeVar('FooOrStr', Foo, str)

def doit(reset: bool, arg: FooOrStr) -> FooOrStr:
    if reset:
        if isinstance(arg, Foo):
            reveal_type(arg)
            arg = Foo()
        elif isinstance(arg, str):
            reveal_type(arg)
            arg = ''
        else:
            raise TypeError()
    return arg
test.py:12: note: Revealed type is 'test.Foo*'
test.py:12: note: Revealed type is 'test.<subclass of "str" and "Foo">'
test.py:13: error: Incompatible types in assignment (expression has type "Foo", variable has type "str")  [assignment]
test.py:15: note: Revealed type is 'builtins.str*'

Based on the latest blog post about 0.770 I suspect this is by design, but what can I do to work around it (short of adding some artificial method to make Foo incompatible with str)?

It would be good to add something to the docs about this, because I think it could be a fairly common trap. Also, I think adjusting the error message to clarify the relationship to multiple inheritance would help, e.g. variable has type Foo and 'test.<subclass of "str" and "Foo">'.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions