Skip to content

MyPy type inference clashes with type annotation #4293

Closed
@alanhdu

Description

@alanhdu

The following code:

import os
from typing import Union, Type

class B():
    pass
class C():
    pass

CLASS: Union[Type[B], Type[C]] = B if "A" in os.environ else C

fails type-checking using mypy==0.550.0 and Python 3.6 with the following error:

Incompatible types in assignment (expression has type "Type[object]", variable has type "Union[Type[B], Type[C]]")

The "use the common base class" as the type is probably a good heuristic in general, but it seems weird that an explicit type annotation with a union fails.

(The context for this is that we have two classes that both implement an ABC interface. At runtime, we switch between them based on some configuration and environment variables, but because MyPy infers the class type as the ABC, we get a Cannot instantiate abstract class error).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions