英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论