python - 参数化泛型不能与类或实例检查一起使用

标签 python pycharm type-hinting

我编写了代码,但在 pycharm(2019.1) 中收到以下消息: “参数化泛型不能与类或实例检查一起使用”

    def data_is_valid(data):
        keys_and_types = {
            'comment': (str, type(None)),
            'from_budget': (bool, type(None)),
            'to_member': (int, type(None)),
            'survey_request': (int, type(None)),
        }

        def type_is_valid(test_key, test_value):
            return isinstance(test_value, keys_and_types[test_key])

        type_is_valid('comment', 3)

我真的不是很理解这个消息。我做错了什么还是pycharm中的错误? 如果我明确地类型转换为元组,错误就会消失。

def type_is_valid(test_key, test_value):
    return isinstance(test_value, tuple(keys_and_types[test_key]))

screenshot

最佳答案

这看起来像是 pycharm 中的一个错误,假设您正在以一种意想不到的方式使用 typing 模块,这有点过于急切了。请在此处查看此示例,其中该假设是正确的:

enter image description here

typing 模块中的类仅在类型注释上下文中有用,不能检查或与实际类进行比较,而这正是 isinstance 试图做的。由于 pycharm 看到一个带有方括号但不包含文字的简单对象,它会跳转到您看到的错误结论。

您的代码很好,您可以按原样使用它。

关于python - 参数化泛型不能与类或实例检查一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56493140/

相关文章:

python - Pycharm:Python Qt代码代码补全

python - 在 Windows 10 上设置 OpenAI Gym

python - "can be converted to"的类型提示是什么意思?

python - 迭代 Pandas 数据框中的多个列并创建新列

python - Django rest 框架使用 httpie 忽略丢失的 csrf token

python - 如何在pycharm中将插入符号移动到控制台?

clojure - 如何键入提示数组?

模块类型的 Python 类型

python - psycopg2 返回 date_part 函数的错误(?)类型

python - google.api_core.exceptions.ServiceUnavailable : 503 Getting metadata from plugin failed with error: 'str' object has no attribute 'before_request'