我正在尝试使用 python 类型注释创建树结构。代码是这样的:
from typing import List
class TNode:
def __init__(self, parent: 'TNode', data: str, children: List['TNode'] = []):
self.parent = parent
self.data = data
self.children = children
root = TNode(None, 'example')
Run Code Online (Sandbox Code Playgroud)
但是代码存在类型不匹配的问题,Pycharm 会引发Expected type 'TNode', got 'None' instead. 有没有办法解决这个问题,或者是否有更好的方法来设计类构造函数?
我在文档中读到 Python 3.5 版本中存在类型提示我在 ipython 终端中编写了两个函数来测试这对“相同”函数意味着什么。
def dostuff(name: str) -> str:
print(str.capitalize())
def do_stuff(name):
print(str.capitalize())
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,调用dostuff('arthur')并do_stuff('arthur')都返回 'Arthur'。
但是,调用do_stuff([])和dostuff([])都返回错误:
AttributeError: 'list' object has no attribute 'capitalize'
Run Code Online (Sandbox Code Playgroud)
这是有道理的,相同的错误在两者中都是有效的,但是为什么类型提示器/检查器实际上没有声明性地声明argument not of type 'str'或其他什么?
另外,如果您定义如下内容:
def do_stuff(name: str) -> str:
return list(name)
Run Code Online (Sandbox Code Playgroud)
即使函数应该返回一个字符串,解释器甚至不会抱怨我返回的是一个列表而不是一个字符串。
我知道这些都是人为的例子,但我做错了什么吗?
我在 python 中有这一行;
set1 = set() # create empty set
Run Code Online (Sandbox Code Playgroud)
当我使用 mypi 扫描时,出现错误 Need type annotation for 'set1'
如何为空集提供类型注释?
我在 pycharm 中使用 python 3.7 和 mypi 插件。
我正在使用 Python 3.7 并有类似的东西
class A(object):
def __init__(self, value: int):
self.value = value
@classmethod
def factory(cls, value: int) -> A:
return A(value=value)
Run Code Online (Sandbox Code Playgroud)
是的,这是一个人为的示例,但我本质上是试图注释工厂函数以声明它返回 的实例,但是,当我尝试 在文件上A运行 linter 时,此操作会失败,因为它抱怨未定义。flake8A
有没有什么方法可以注释这个函数,这样 linter 就不会抱怨?
我的 python 代码中有这样的定义:
options = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))
options['modem1']['ByCost'] = ...
options['modem1']['ByCarrier'] = ...
options['modem1']['BySimSignal'] = ...
options['modem1']['SwitchBackByTimer'] = ...
Run Code Online (Sandbox Code Playgroud)
在我的预提交/mypy 检查期间它失败了,因为消息如下:
Need type annotation for 'options'
Run Code Online (Sandbox Code Playgroud)
由于我没有看到这段代码有任何问题,那么有什么解决办法可以让它通过 mypy 检查这一行吗?
顺便说一句,除了在我的代码中设置之外,我正在寻找其他方法:
disable_error_codes with error code var-annotated
Run Code Online (Sandbox Code Playgroud)
多谢 !
杰克
Mypy 认为这对以下情况有效strict = true:
from typing import Dict, TypeVar
KeyType = TypeVar("KeyType")
ValueType = TypeVar("ValueType")
class InvertibleDict(Dict[KeyType, ValueType]):
def __inverse__(self) -> "InvertibleDict[ValueType, KeyType]":
new_instance: "InvertibleDict[ValueType, KeyType]" = self.__class__()
for key, value in self.items():
new_instance[value] = key
return new_instance
Run Code Online (Sandbox Code Playgroud)
但是,它不接受相同代码的以下更简洁版本,在最后一行说“关键字必须是字符串”:
from typing import Dict, TypeVar
KeyType = TypeVar("KeyType")
ValueType = TypeVar("ValueType")
class InvertibleDict(Dict[KeyType, ValueType]):
def __inverse__(self) -> "InvertibleDict[ValueType, KeyType]":
return self.__class__(**{value: key for key, value in self.items()})
Run Code Online (Sandbox Code Playgroud) 我想做以下事情:
from typing import Union, Literal
YES = 1
NO = 0
ValidResponse = Union[Literal[YES], Literal[NO]]
Run Code Online (Sandbox Code Playgroud)
当然,Python 不会让我这样做,因为YES和NO被认为是变量,而不是文字数字。
显然我可以做到ValidResponse = Union[Literal[1], Literal[0]],但作为稍后编辑此文件的程序员,为了更改YES使用的常量(例如YES = 'yes'),我需要在两个不同的地方更改它,这似乎很奇怪。
处理这种情况的最佳方法是什么?
我正在从事我的一个宠物项目,发现了这个小问题。我想在基类中使用类型,问题是类方法的返回类型是由子类设置的字段定义的。这是我的基类
class BaseRepository(metaclass=RequiredAttributes('model')):
model = None # The subclasses have to define the this field with a class type.
# All the class methods will return objects of the same
# type as this field.
def get(self, id) -> ??:
# return an object of the type defined in mode
...
class UserRepo(BaseRepository): # subclass
model = User # class type
...
Run Code Online (Sandbox Code Playgroud)
我想将函数的类型设置get为与模型字段中定义的对象类型相同。
关于如何完成类似的事情有什么建议吗?
我有一个函数返回另一个函数,但返回函数的返回类型不清楚。为了表达我们可以使用的函数返回类型Callable[[], ReturnType],并且不强调参数,我们可以这样做Callable[..., ReturnType]。但我希望这ReturnType不是确定的。
我该怎么办?
我的代码是这样的:
def funcA() -> int:
return 2
def funcB() -> str:
return 'b'
def f(inp: int) -> Callable[[], X] # <--- what should X be Here?
return funcA if inp == 0 else funcB
Run Code Online (Sandbox Code Playgroud) 我有一个函数,它接收一个类并返回该类的一个实例。一个简单的例子:
def instantiate(class_: Type[enum.Enum], param: str) -> enum.Enum:
return class_(param)
Run Code Online (Sandbox Code Playgroud)
返回值与参数的类型相同class_,因此如果 class_ 是MyEnum,则返回值将是类型MyEnum。
有什么方法可以声明吗?
python ×10
python-typing ×10
python-3.x ×6
type-hinting ×5
mypy ×2
flake8 ×1
pydantic ×1
types ×1