Title: __new__ type annotations have unexpected behavior in some cases · Issue #9482 · python/mypy · GitHub
Open Graph Title: __new__ type annotations have unexpected behavior in some cases · Issue #9482 · python/mypy
X Title: __new__ type annotations have unexpected behavior in some cases · Issue #9482 · python/mypy
Description: Bug Report I am trying to emulate some Pandas type behavior, where Index.__new__ can return different types. The simplified case I am trying to model is that sequences of np.datetime64 and datetime.datetime get turned into one class, and...
Open Graph Description: Bug Report I am trying to emulate some Pandas type behavior, where Index.__new__ can return different types. The simplified case I am trying to model is that sequences of np.datetime64 and datetime...
X Description: Bug Report I am trying to emulate some Pandas type behavior, where Index.__new__ can return different types. The simplified case I am trying to model is that sequences of np.datetime64 and datetime...
Opengraph URL: https://github.com/python/mypy/issues/9482
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"__new__ type annotations have unexpected behavior in some cases","articleBody":"**Bug Report**\r\n\r\nI am trying to emulate some Pandas type behavior, where `Index.__new__` can return different types. The simplified case I am trying to model is that sequences of `np.datetime64` and `datetime.datetime` get turned into one class, and other objects get turned into another class.\r\n\r\nThe following is the only way I've gotten it to work, after trying many many variations:\r\n\r\n```python\r\n# THIS VERSION WORKS, BUT REQUIRES MODIFYING CODE WITH EXTRA CLASS\r\nfrom typing import TypeVar, Generic, List, Union, overload\r\nfrom typing_extensions import Protocol\r\nfrom datetime import datetime\r\n\r\nT = TypeVar(\"T\", covariant=True)\r\nS = TypeVar(\"S\")\r\n\r\nclass datetime64(int):\r\n \"\"\"Stand-in for np.datetime64.\"\"\"\r\n\r\n\r\nclass IndexType(Protocol[T]):\r\n def first(self) -> T: ...\r\n\r\n\r\nclass Index:\r\n\r\n @overload\r\n def __new__(cls, values: List[datetime64]) -> \"Datetime64Index\": ...\r\n @overload\r\n def __new__(cls, values: List[datetime]) -> \"Datetime64Index\": ...\r\n @overload\r\n def __new__(cls, values: List[S]) -> \"DefaultIndex[S]\": ...\r\n\r\n def __new__(cls, values):\r\n if type(values[0]) in (datetime, datetime64):\r\n cls = Datetime64Index\r\n else:\r\n cls = DefaultIndex\r\n return object.__new__(cls)\r\n\r\n\r\nclass DefaultIndex(Index, Generic[S]):\r\n def __init__(self, values: List[S]):\r\n self.values = values\r\n\r\n def first(self) -> S:\r\n return self.values[0]\r\n\r\n\r\nclass Datetime64Index(DefaultIndex):\r\n\r\n def __init__(self, values: Union[List[datetime], List[datetime64]]):\r\n self.values : List[datetime64] = [\r\n datetime64(o.timestamp()) if isinstance(o, datetime) else o\r\n for o in values\r\n ]\r\n\r\n def first(self) -> datetime:\r\n return datetime.fromtimestamp(self.values[0])\r\n\r\n\r\n# Should work\r\na: IndexType[datetime] = Index([datetime64(100)])\r\nb: IndexType[datetime] = Index([datetime(2000, 10, 20)])\r\nc: IndexType[bool] = Index([True])\r\n\r\n# Should complain\r\nd: IndexType[datetime] = Index([\"a\"])\r\ne: IndexType[bool] = Index([\"a\"])\r\n```\r\n\r\nAs expected, mypy only complains about the last two lines:\r\n\r\n```\r\n$ mypy test.py\r\ntest.py:59: error: List item 0 has incompatible type \"str\"; expected \"datetime64\"\r\ntest.py:60: error: Incompatible types in assignment (expression has type \"Datetime64Index\", variable has type \"IndexType[bool]\")\r\ntest.py:60: note: Following member(s) of \"Datetime64Index\" have conflicts:\r\ntest.py:60: note: Expected:\r\ntest.py:60: note: def first(self) -> bool\r\ntest.py:60: note: Got:\r\ntest.py:60: note: def first(self) -> datetime\r\ntest.py:60: error: List item 0 has incompatible type \"str\"; expected \"datetime64\"\r\n```\r\n\r\nHowever, the need for `DefaultIndex` feels like a hack. What I would actually like to do is the following:\r\n\r\n```python\r\n# THIS VERSION SHOULD WORK, BUT CAUSES MYPY TO ERRONEOUSLY(?) COMPLAIN\r\nfrom typing import TypeVar, Generic, List, Union, overload\r\nfrom typing_extensions import Protocol\r\nfrom datetime import datetime\r\n\r\nT = TypeVar(\"T\", covariant=True)\r\nS = TypeVar(\"S\")\r\n\r\nclass datetime64(int):\r\n \"\"\"Stand-in for np.datetime64.\"\"\"\r\n\r\n\r\nclass IndexType(Protocol[T]):\r\n def first(self) -> T: ...\r\n\r\n\r\nclass Index(Generic[S]):\r\n\r\n @overload\r\n def __new__(cls, values: List[datetime64]) -> \"Datetime64Index\": ...\r\n @overload\r\n def __new__(cls, values: List[datetime]) -> \"Datetime64Index\": ...\r\n @overload\r\n def __new__(cls, values: List[S]) -> \"Index[S]\": ...\r\n\r\n def __new__(cls, values):\r\n if type(values[0]) in (datetime, datetime64):\r\n cls = Datetime64Index\r\n return object.__new__(cls)\r\n\r\n def __init__(self, values: List[S]):\r\n self.values = values\r\n\r\n def first(self) -> S:\r\n return self.values[0]\r\n\r\n\r\nclass Datetime64Index(Index):\r\n\r\n def __init__(self, values: Union[List[datetime], List[datetime64]]):\r\n self.values : List[datetime64] = [\r\n datetime64(o.timestamp()) if isinstance(o, datetime) else o\r\n for o in values\r\n ]\r\n\r\n def first(self) -> datetime:\r\n return datetime.fromtimestamp(self.values[0])\r\n\r\n\r\n# Should work\r\na: IndexType[datetime] = Index([datetime64(100)])\r\nb: IndexType[datetime] = Index([datetime(2000, 10, 20)])\r\nc: IndexType[bool] = Index([True])\r\n\r\n# Should complain\r\nd: IndexType[datetime] = Index([\"a\"])\r\ne: IndexType[bool] = Index([\"a\"])\r\n```\r\n\r\nHowever, mypy gets confused and complains about `a: IndexType[datetime] = Index([datetime64(100)])`:\r\n\r\n```$ mypy test.py\r\ntest.py:50: error: List item 0 has incompatible type \"datetime64\"; expected \"datetime\"\r\ntest.py:55: error: List item 0 has incompatible type \"str\"; expected \"datetime\"\r\ntest.py:56: error: List item 0 has incompatible type \"str\"; expected \"bool\"\r\nFound 3 errors in 1 file (checked 1 source file)\r\n\r\n```\r\n\r\n**Your Environment**\r\n\r\n- Mypy version used: 0.782\r\n- Mypy command-line flags: None\r\n- Mypy configuration options from `mypy.ini` (and other config files): None\r\n- Python version used: 3.7\r\n- Operating system and version: Linux","author":{"url":"https://github.com/itamarst","@type":"Person","name":"itamarst"},"datePublished":"2020-09-25T14:53:44Z","url":"https://github.com/python/mypy/issues/9482"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:11115353-cf04-8648-f5a7-d6f7d3d61b59 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B676:3DAD59:1966E9E:218D927:6B0024DB |
| html-safe-nonce | 1ae3b669b0c05a06cad02d0dd8d8a30ccb77d5f3e69601fdbfd21fd927cb204a |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCNjc2OjNEQUQ1OToxOTY2RTlFOjIxOEQ5Mjc6NkIwMDI0REIiLCJ2aXNpdG9yX2lkIjoiNTkxNzIzNTIwMDY0Njk4MDgyNyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 1488ec685a149efa08cd24b8aef54157f97e3334b0f358e3ef22eb378737a117 |
| hovercard-subject-tag | issue:709003303 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/mypy/9482/issue_layout |
| twitter:image | https://opengraph.githubassets.com/096f6142e2a80794f1bf6a0a1bcb1766f80a300cda8818fe8a581bc8e07dac30/python/mypy/issues/9482 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/096f6142e2a80794f1bf6a0a1bcb1766f80a300cda8818fe8a581bc8e07dac30/python/mypy/issues/9482 |
| og:image:alt | Bug Report I am trying to emulate some Pandas type behavior, where Index.__new__ can return different types. The simplified case I am trying to model is that sequences of np.datetime64 and datetime... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | itamarst |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4eb4cba0d69f045374ac15de9666d22b0961e1d555cc3824f36b7734c00c78e0 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/mypy git https://github.com/python/mypy.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 7053637 |
| octolytics-dimension-repository_nwo | python/mypy |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 7053637 |
| octolytics-dimension-repository_network_root_nwo | python/mypy |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 44c658b24abf00491fb7ae5f56d42c9f38cbeab2 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width