如果我在字典中有一个带有无效标识符的键,例如A(2). 如何TypedDict使用此字段创建一个?
例如
from typing import TypedDict
class RandomAlphabet(TypedDict):
A(2): str
Run Code Online (Sandbox Code Playgroud)
不是有效的 Python 代码,导致错误:
from typing import TypedDict
class RandomAlphabet(TypedDict):
A(2): str
Run Code Online (Sandbox Code Playgroud)
保留关键字也有同样的问题:
class RandomAlphabet(TypedDict):
return: str
Run Code Online (Sandbox Code Playgroud)
抛出:
SyntaxError: illegal target for annotation
Run Code Online (Sandbox Code Playgroud) 我可以为 python 中的函数参数指定特定的字典形状/形式吗?
就像在打字稿中一样,我指示info参数应该是带有字符串name和数字的对象age:
function parseInfo(info: {name: string, age: number}) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
有没有办法用 python 函数来做到这一点,否则:
def parseInfo(info: dict):
# function body
Run Code Online (Sandbox Code Playgroud)
或者这可能不是Pythonic,我应该使用命名关键字或类似的东西?
在将字典声明为文字时,有没有办法输入提示我期望特定键的值?
然后,讨论:在python中有关于字典输入的指导原则吗?我想知道在词典中混合类型是否被认为是不好的做法.
这是一个例子:
考虑在类中声明字典__init__:
(免责声明:我在实例中意识到,某些.elements条目可能更适合作为类属性,但这是为了示例).
class Rectangle:
def __init__(self, corners: Tuple[Tuple[float, float]], **kwargs):
self.x, self.z = corners[0][0], corners[0][1]
self.elements = {
'front': Line(corners[0], corners[1]),
'left': Line(corners[0], corners[2]),
'right': Line(corners[1], corners[3]),
'rear': Line(corners[3], corners[2]),
'cog': calc_cog(corners),
'area': calc_area(corners),
'pins': None
}
class Line:
def __init__(self, p1: Tuple[float, float], p2: Tuple[float, float]):
self.p1, self.p2 = p1, p2
self.vertical = p1[0] == p2[0]
self.horizontal = p1[1] == p2[1]
Run Code Online (Sandbox Code Playgroud)
当我键入以下类型
rec1 = Rectangle(rec1_corners, show=True, name='Nr1')
rec1.sides['f...
Run Code Online (Sandbox Code Playgroud)
Pycharm会建议'front' 我.更好的是,当我这样做时
rec1.sides['front'].ver... …Run Code Online (Sandbox Code Playgroud) 尝试在Python代码中使用静态类型,这样mypy可以帮助我解决一些隐藏的错误.使用单个变量非常简单
real_hour: int = lower_hour + hour_iterator
Run Code Online (Sandbox Code Playgroud)
更难以将它与列表和词典一起使用,需要导入额外的typing库:
from typing import Dict, List
hour_dict: Dict[str, str] = {"test_key": "test_value"}
Run Code Online (Sandbox Code Playgroud)
但主要问题 - 如何使用不同值类型的Dicts,如:
hour_dict = {"test_key": "test_value", "test_keywords": ["test_1","test_2"]}
Run Code Online (Sandbox Code Playgroud)
如果我不对这样的词典使用静态类型 - mypy会显示错误,例如:
len(hour_dict['test_keywords'])
- Argument 1 to "len" has incompatible type
Run Code Online (Sandbox Code Playgroud)
那么,我的问题是:如何在这些词典中添加静态类型?:)
给定一个我想使用类型提示增强的函数(在 Python 3.9 中):
def my_func():
return my_dict.keys() # origin of my_dict is irrelevant
Run Code Online (Sandbox Code Playgroud)
我看过PEP 589和这个 Stack Overflow 问题,描述了如何使用TypedDict. 然而,这不是我试图实现的目标。
我想要字典键对象的返回类型。我知道可以使用将键对象转换为列表list(my_dict),然后使用返回类型list[key_type](使用key_typebeingint等str)。但这是要走的路吗?
my_dict>>> type(my_dict.keys())
<class 'dict_keys'>
Run Code Online (Sandbox Code Playgroud)
但是,我无法dict_keys像这样使用:
def my_func() -> dict_keys:
return my_dict.keys()
Run Code Online (Sandbox Code Playgroud)
Pylance 报告说,该my_dict.keys()类型属于_dict_keys[key_type, value_type]。为什么这种类型应该是“私有的”?它来自哪里?我们可以以某种方式使用它作为返回类型吗?
我有一个 python 函数,它返回具有以下结构的字典
{
(int, int): {string: {string: int, string: float}}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何使用类型提示来指定它。所以,这些位很清楚:
Dict[Tuple[int, int], Dict[str, Dict[str, # what comes here]]
Run Code Online (Sandbox Code Playgroud)
但是,内部字典具有两个键的int和值类型。float我不知道如何注释
我有一些 Python 3.7 代码,我正在尝试向其中添加类型。我想添加的类型之一实际上是Union几种可能的字符串之一:
from typing import Union, Optional, Dict
PossibleKey = Union["fruits", "cars", "vegetables"]
PossibleType = Dict[PossibleKey, str]
def some_function(target: Optional[PossibleType] = None):
if target:
all_fruits = target["fruits"]
print(f"I have {all_fruits}")
Run Code Online (Sandbox Code Playgroud)
这里的问题是 Pyright 抱怨的PossibleKey。它说:
“水果没有定义”
我想让 Pyright/Pylance 工作。
我已经from enum import Enum从另一个 SO 答案中检查了该模块,但是如果我尝试这样做,我最终会遇到更多问题,因为我实际上处理的是 aDict[str, Any]而不是Enum.
表示我的类型的正确 Pythonic 方式是什么?
python ×7
python-3.x ×3
typing ×3
dictionary ×2
type-hinting ×2
mypy ×1
pycharm ×1
pylance ×1
pyright ×1
types ×1