Skip to content

mypy incorrectly infers the type of a variable from different branches #4061

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
igalic opened this issue Oct 5, 2017 · 5 comments
Closed

Comments

@igalic
Copy link

igalic commented Oct 5, 2017

in the following code,

@click.argument("filters", nargs=-1)
def cli(ctx,
        release: bool=False) -> None:
…
    if release is True:
        resources_class = iocage.lib.Releases.ReleasesGenerator
    else:
        resources_class = iocage.lib.Jails.JailsGenerator

    resources = resources_class(
        filters=filters,
        host=host,
        logger=logger
    )
…

mypy will issue the error:

iocage/cli/destroy.py:69:8: error: Incompatible types in assignment (expression has type Type[JailsGenerator], variable has type Type[ReleasesGenerator])

Also note that both, JailsGenerator and ReleaseGenerator inherit from the same common class Resource.

@ilevkivskyi
Copy link
Member

Different people have different opinions about what should be inferred for resource_class: should it be a union? a common base class? just an error? A good idea is to give an explicit annotation:

    resource_class: Type[Resource]
    if release is True:
        resources_class = iocage.lib.Releases.ReleasesGenerator
    else:
        resources_class = iocage.lib.Jails.JailsGenerator

@igalic
Copy link
Author

igalic commented Oct 5, 2017

This doesn't seem to work.
The error remains the same.

@JukkaL
Copy link
Collaborator

JukkaL commented Oct 5, 2017

What about this:

    resource_class: Union[Type[iocage.lib.Releases.ReleasesGenerator],
                          Type[iocage.lib.Jails.JailsGenerator]]
    if release is True:
        resources_class = iocage.lib.Releases.ReleasesGenerator
    else:
        resources_class = iocage.lib.Jails.JailsGenerator

@ilevkivskyi
Copy link
Member

@igalic

This doesn't seem to work.
The error remains the same.

Strange, I just tried this code on master and it works perfectly:

class A: ...
class B(A): ...
class C(A): ...

resource: Type[A]
if bool():
    resource = B
else:
    resource = C

@igalic
Copy link
Author

igalic commented Oct 5, 2017

okay! updated to mypy! to i can no longer say if this was the cause of my error, or the fact that i wrote resource_class instead of resources_class._.

thank you all for you help and patience 💜💜💜

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