Skip to content
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

Strict type checking like if type(x) is T: leads to wrong type restrictions #572

Closed
Azureblade3808 opened this issue Nov 6, 2020 · 2 comments
Labels
bug Something isn't working fixed in next version (main) A fix has been implemented and will appear in an upcoming version

Comments

@Azureblade3808
Copy link

Environment data

  • Language Server version: Pylance 2020.11.0
  • OS and version: Window 7
  • Python version (& distribution if applicable, e.g. Anaconda): Python 3.8.5

Actual Behavior

I have written a function to cast instances of any sub-classes of datetime.date as direct instances of datetime.date, so they can be used as SQL parameters.

import datetime as dt

def cast_as_builtin_date(date: dt.date) -> dt.date:
    if type(date) is dt.date:
        return date

    # Pylance says the type of `date` from now on will be 'Never',
    # but it still can necessarily be any sub-class of `datetime.date`
    # except for `datetime.date` itself.
    return dt.date(date.toordinal())

The type of argument date after the type check is determined as "Never" by Pylance, and as a result, the call of date.toordinal() is regarded problematic. It seems that Pylance treats if type(x) is T: just the same as if isinstance(x, T):, although they are different in some degrees.

Code Snippet / Additional Information

As a side note, code like if type(x) == T and if T is type(x) works just fine and can be used as a work-around.

@github-actions github-actions bot added the triage label Nov 6, 2020
@erictraut
Copy link
Contributor

Thanks for the bug report. This will be fixed in the next release.

@erictraut erictraut added bug Something isn't working fixed in next version (main) A fix has been implemented and will appear in an upcoming version and removed triage labels Nov 6, 2020
@jakebailey
Copy link
Member

This issue has been fixed in version 2020.11.1, which we've just released. You can find the changelog here: https://github.com/microsoft/pylance-release/blob/master/CHANGELOG.md#2020111-11-november-2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixed in next version (main) A fix has been implemented and will appear in an upcoming version
Projects
None yet
Development

No branches or pull requests

3 participants