标签: python-typing

在 python 中使用类型别名然后将其声明为变量是一个好主意吗?

我正在看这样的代码:

class DeckManager:

   decks: Dict[str, Any]

   def __init__(self, col: a) -> None:

        self.decks = {}
Run Code Online (Sandbox Code Playgroud)

Decks: Dict[str, Any] 指定类型别名是否正确?如果是这样,那么稍后在代码中使用 self.decks 是否有意义。这不是很混乱吗?

python python-3.x python-typing

3
推荐指数
1
解决办法
3986
查看次数

如何访问父类的 __annotations__ ?

有什么办法可以访问父类的类型__注解__吗?

在上面的示例中,该类Student继承自 class Person,但它不包含该类的类型注释Person

class Person:
    name: str
    address: str

    def __init__(self):
        print(self.__annotations__)


class Student(Person):
    year: int


person = Person()
# {'name': <class 'str'>, 'address': <class 'str'>}

student = Student()
# {'year': <class 'int'>}
# HERE I would expect the name and the address props
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-typing

3
推荐指数
1
解决办法
1955
查看次数

具有不同 kwargs 的函数的回调协议

我有一个将callback函数作为参数的函数:

def function(arg1: int, callback):
    ...
Run Code Online (Sandbox Code Playgroud)

我正在尝试为该函数添加类型提示callback。现在,传递给该函数的回调函数具有相同的位置参数,但 kwargs 可以完全不同(类型和名称)。

def function1(arg1: int, arg2: str, **kwargs1):
    ...

def function2(arg1: int, arg2: str, **kwargs2):
    ...
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个适合这两个函数的回调协议,但到目前为止,我还没有找到一种方法可以在 kwargs 不同时使其工作。在这种情况下有没有办法创建统一的回调协议?

python callback type-hinting python-3.x python-typing

3
推荐指数
1
解决办法
2254
查看次数

Python 类型,mypy 根据类方法返回类型推断返回类型

考虑当我有不同的类实现相同的方法但返回不同类型时的情况。

class A:
    def method(self) -> float:
        return 3.14

class B:
    def method(self) -> str:
        return 'a string'

def do_method(x):
    return x.method()

r = do_method(A())
reveal_type(r)  # Revealed type is 'Any'
Run Code Online (Sandbox Code Playgroud)

Mypy 无法推断函数的确切返回类型do_method(),这取决于其参数x。我如何帮助 Mypy 实现这一目标?

注意:还请考虑到我想与该函数一起使用的此类类的数量do_method()太多,因此不想将它们全部更改。

python mypy python-typing

3
推荐指数
1
解决办法
3006
查看次数

如何在 Python 中输入两个类的并集列表作为参数

我正在尝试创建一个函数,它接受哺乳动物列表或动物列表作为参数。

这是我的代码

from typing import Union, List
class Animals():
    pass
class Mammels(Animals):
    pass

def add_mammel(x : List[Union[Animals, Mammels]]):
    x.append(Mammels())

l = [Mammels(), Mammels()]
add_mammel(l)
print(l)
Run Code Online (Sandbox Code Playgroud)

这段代码有效,但是当我用 mypy 检查它时,我得到以下内容

python -m mypy fourth.py
fourth.py:11: error: Argument 1 to "add_mammel" has incompatible type "List[Mammels]"; expected "List[Union[Animals, Mammels]]"
fourth.py:11: note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
fourth.py:11: note: Consider using "Sequence" instead, which is covariant
Run Code Online (Sandbox Code Playgroud)

这个问题与“方差”有关,但我无法弄清楚这真正意味着什么。

type-hinting python-3.x mypy python-typing

3
推荐指数
1
解决办法
5384
查看次数

基类和继承类的类型注释 - Generic 和 TypeVar 是正确的方法吗?

假设我有一个基类

from typing import List, Optional

class Node:
    def __init__(self, name: str) -> None:
        self.name = name
        self.children: List['Node'] = []
    ...
Run Code Online (Sandbox Code Playgroud)

和一个子类

class PropertiesNode(Node):
    def __init__(
        self, name: str, properties: List[str], inherit: Optional['PropertiesNode']
    ) -> None:
        Node.__init__(self, name)
        self.properties = set(properties)
        if inherit:
            self.properties.update(inherit.properties)
            self.children = deepcopy(inherit.children)
            for child in self.children:
                child.properties.update(properties)
                # ^ ERR: "Node" has no attribute "properties"  [attr-defined]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,mypy(正确地)在那里标记了一个错误,因为Node.children明确给出了List[Node].

所以我阅读了泛型类型,在我看来,解决方案是使用TypeVars 和Generic

from typing import Generic, List, Optional, TypeVar …
Run Code Online (Sandbox Code Playgroud)

python generics type-hinting mypy python-typing

3
推荐指数
1
解决办法
4782
查看次数

使用 types.Literal 的正确方法是什么?

我的代码看起来像这样,BDW 运行良好,没有任何错误

from typing import Literal

def verify(word: str) -> Literal['Hello XY']:
    a = 'Hello ' + word
    return a

a = verify('XY')
Run Code Online (Sandbox Code Playgroud)

虽然,当我尝试使用 mypy 进行类型检查时,它会抛出错误error: Incompatible return value type (got "str", expected "Literal['Hello XY']")

注意:要执行类型检查mypy ./filename.py,只需在 pip 安装 mypy 后执行 。

另外,当我这样做时,类型检查工作正常

from typing import Literal

def verify(word: str) -> Literal['Hello XY']:
    a = 'Hello ' + word
    return 'Hello XY' #changed here

a = verify('XY')
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

python typechecking type-hinting mypy python-typing

3
推荐指数
1
解决办法
6729
查看次数

~&lt;type&gt; 有什么作用?

在编写代码时,我遇到过表达类型的 linter ~<type>(其中<type>类型不是<type>文学的)。一个例子是self

class A:
    def foo(self):
        reveal_type(self) # reveals "~A"
Run Code Online (Sandbox Code Playgroud)

我认为这意味着“A或”的子类A;但是,我在网上找不到任何有关它的信息。

另外,您不能在代码中使用以下语法:

a: ~A # raises an exception: TypeError: bad operand type for unary ~: 'type'
Run Code Online (Sandbox Code Playgroud)

如果a会被揭露的话那就是了Unknown

python type-hinting mypy python-typing

3
推荐指数
1
解决办法
261
查看次数

如何指定 itertools groupby 的类型?

我有一个要操作的字符串列表。返回类型类似于组类型,由 int 作为键和字符串列表作为值组成。

我试过什么?

from typing import List, Dict, Iterator

from itertools import groupby

def group_names(names: List[str]) -> Dict[int, list]:
    group_iter: Iterator[int, Iterator[list]]  = groupby(sorted(names,key=len), lambda x: len(x)) # -> Having an issue here
    return {k: list(v) for k, v in group_iter}

Run Code Online (Sandbox Code Playgroud)

它工作正常,我将其输入为由 Any 类型组成的迭代器。

group_iter: Iterator[Any]  = groupby(sorted(names,key=len), lambda x: len(x))
Run Code Online (Sandbox Code Playgroud)

但我想指定组键和项目的类型?

python-itertools python-3.x python-typing

3
推荐指数
1
解决办法
790
查看次数

可能无法加载的模块中的类型的类型提示?

如何定义类型提示以在未导入 Geopandas 时仍将 GeoPandas GeoDataFrame 指定为选项而不是错误?IE:在不存在模块的情况下定义类型提示

给定一个采用 DataFrame 或 GeoDataFrame 类型的参数的类,通常只会导入 Pandas,但有时 GeoPandas 也会被导入。

该类必须能够互换地从任一框架中获取框架。如果参数定义为:Union[pandas.Dataframe, geopandas.geodataframe.GeoDataFrame]未导入GeoPandas时会出错,反之亦然。Pandas 或 Geopandas 不会仅仅为了类型提示的目的而被导入。

Any是定义 geopandas 数据框的选项,但我希望更简洁。Union[pandas.Dataframe, Any]感觉毫无意义,因为它不提供关于替代参数可能是什么类型的上下文,并且不涵盖加载 Geopandas 而不是 Pandas 时的情况。

我已经查看了如何通过可选导入输入提示?但这不是同一个情况。

python python-typing

3
推荐指数
1
解决办法
500
查看次数