程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Python generic type on function getting lost somewhere

发布于2024-12-08 09:47     阅读(482)     评论(0)     点赞(28)     收藏(2)


Getting this typing error:

error: Incompatible types in assignment (expression has type "object", variable has type "A | B")  [assignment]

With this code:

from dataclasses import dataclass
from typing import TypeVar, Mapping, reveal_type


@dataclass
class A:
    foo: str = "a"

@dataclass
class B:
    bar: str = "b"

lookup_table: Mapping[str, type[A] | type[B]] = {
    "a": A,
    "b": B
}

reveal_type(lookup_table)  # note: Revealed type is "typing.Mapping[builtins.str, Union[type[simple.A], type[simple.B]]]"
T = TypeVar("T")

def load(lookup_table: Mapping[str, type[T]], lookup_key:str) -> T:
    con: type[T] = lookup_table[lookup_key]
    instance: T = con()
    return instance

example_a: A | B = load(lookup_table, "a")  # error: Incompatible types in assignment (expression has type "object", variable has type "A | B")
print(example_a)

Edit: Logged a mypy bug here: https://github.com/python/mypy/issues/18265


解决方案


The error occurs because the load function is returning either (A|B) which is not detected by the type checker in that function, as it was expecting an object . Therefore, it is giving an error of incompatible types.



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2046415/1cf5b5949fb58bb07390/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)