找出一个方法的返回,该方法在某些条件下返回空哈希。

huangapple go评论131阅读模式
英文:

Figure out return of a method that returns empty hash on some condition

问题

def someMethod() -> dict[any, any]:
    if not os.path.exists('some path'):
        return {}

    config = {'a': 1, 'b': 2}
    return config

我正在尝试理解如何使这个工作:

def someMethod() -> dict[any, any]:
    if not os.path.exists('some path'):
        return {}

    config = {'a': 1, 'b': 2}
    return config

我认为那是不正确的。看到这个错误 - Declared return type, "dict[Unknown, Unknown]", is partially unknownPylance

这个想法是如果路径不存在(或某些条件)或者包含键值对的正确字典,就返回空字典。

有什么建议吗?

英文:

I'm trying to understand how to make this work:

def someMethod() -> dict[any, any]:
    if not os.path.exists('some path'):
        return {}

    config = {'a': 1, 'b': 2}
    return config

I don't think that's correct. Seeing this error - Declared return type, "dict[Unknown, Unknown]", is partially unknownPylance

The idea is to return empty dict if a path doesn't exist (or on some condition) or correct dict with key-value pairs.

Any ideas?

答案1

得分: 5

小写的 "any" 是 Python 内置函数,而不是一种类型。相反,您需要从 typing 模块导入大写的 "Any"。

from typing import Any
import os

def someMethod() -> dict[Any, Any]:
    if not os.path.exists('some path'):
        return {}

    config = {'a': 1, 'b': 2}
    return config
英文:

Lowercase any is a Python built-in function and not a type. Instead, you have to import capital Any from the typing module.

from typing import Any
import os

def someMethod() -> dict[Any, Any]:
    if not os.path.exists('some path'):
        return {}

    config = {'a': 1, 'b': 2}
    return config

huangapple
  • 本文由 发表于 2023年5月29日 22:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定