标签: python-typing

如何在Python类型提示中表达多重继承?

在Java C#中,泛型方法可以具有带约束的类型参数,以定义必须实现的接口。

static <T extends Iterable<Integer> & Comparable<Integer>> void test(T p) {

}
Run Code Online (Sandbox Code Playgroud)

在Python中,如果我想使用类型提示来指定变量必须继承类A和B,我该怎么做?我检查了输入模块,它只有一个Union,这意味着变量的类型可以是任何提示,而不能是所有提示。

创建一个继承A和B的新类C似乎是一个解决方案,但看起来很麻烦。

python python-typing

10
推荐指数
1
解决办法
673
查看次数

列表子类的 Python 类型

我希望能够定义列表子类的内容。该类将如下所示。

class A(list):
   def __init__(self):
      list.__init__(self)
Run Code Online (Sandbox Code Playgroud)

我想包括打字,以便发生以下情况。

import typing

class A(list: typing.List[str]):  # Maybe something like this
   def __init__(self):
      list.__init__(self)

>> a = A()
>> a.append("a")  # No typing error
>> a.append(1)  # Typing error
Run Code Online (Sandbox Code Playgroud)

python list subclass python-3.x python-typing

10
推荐指数
1
解决办法
2554
查看次数

如何将 python 类型注释添加到烧瓶全局上下文 g?

我有一个装饰器,可以将用户添加到 Flask 全局上下文 g:

class User:
    def __init__(self, user_data) -> None:
        self.username: str = user_data["username"]
        self.email: str = user_data["email"]

def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        user_data = get_user_data()
        user = User(user_data)
        g.user = User(user_data)

        return f(*args, **kwargs)

    return wrap
Run Code Online (Sandbox Code Playgroud)

我希望在控制器中访问 g.user 时知道 g.user 的类型(用户)。我怎样才能做到这一点?(我正在使用pyright)

python flask mypy python-typing pyright

10
推荐指数
2
解决办法
1793
查看次数

描述枚举名称的字符串文字联合的类型表达式?

鉴于:

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
Run Code Online (Sandbox Code Playgroud)

Foo是否存在这样的类型表达式:

Foo[Color] = Literal["RED", "GREEN", "BLUE"]
Run Code Online (Sandbox Code Playgroud)

python enums python-typing

10
推荐指数
2
解决办法
6804
查看次数

处理Python中缺少非空断言运算符的问题

我想允许 Mypy'strict_optional标志。但是,请考虑一下:

emails = [get_user(uuid).email for uuid in user_uuids]
Run Code Online (Sandbox Code Playgroud)

理论上get_user可以返回None,但在这个用例中,我知道它不能(如果确实如此,我也可以得到异常)。这必须变成:

emails = []
for uuid in user_uuids:
    user = get_user(uuid)
    assert user is not None
    emails.append(user.email)
Run Code Online (Sandbox Code Playgroud)

在 TypeScript 中,有一个非空断言运算符,它允许您仅添加 a !(如getUser(uuid)!.email)。

有没有更好或更优雅的方法来处理这个问题?

python mypy python-typing

10
推荐指数
1
解决办法
2771
查看次数

在为函数分配新属性时,如何抑制 mypy 中的“没有属性”错误?

我经常使用以下习惯用法进行静态初始化:

def compute_answer() -> int:
    if compute_answer.ret is None:
        # Do stuff that only happens the first time
        compute_answer.ret = 42
    return compute_answer.ret

compute_answer.ret = None
Run Code Online (Sandbox Code Playgroud)

但是,使用 mypy 进行类型检查会出现以下错误:

compute.py:2: error: "Callable[[], int]" has no attribute "ret"
compute.py:4: error: "Callable[[], int]" has no attribute "ret"
compute.py:5: error: "Callable[[], int]" has no attribute "ret"
compute.py:7: error: "Callable[[], int]" has no attribute "ret"
Run Code Online (Sandbox Code Playgroud)

如何抑制这些错误,尤其是本地错误(例如,仅此函数/属性)?

python typechecking static-initialization mypy python-typing

10
推荐指数
1
解决办法
6630
查看次数

如何使用python 3.9的typing.Annotation MaxLen?

我知道有一种新的类型格式,Annotated您可以在其中为函数的入口变量指定一些元数据。从文档中,您可以指定传入列表的最大长度,例如:

  • Annotated 可以与嵌套和通用别名一起使用:
T = TypeVar('T')
Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
V = Vec[int]

V == Annotated[list[tuple[int, int]], MaxLen(10)]
Run Code Online (Sandbox Code Playgroud)

但我无法完全理解到底是什么MaxLen。你应该从其他地方导入一个类吗?我尝试过导入typing.MaxLen,但似乎不存在(我正在使用Python 3.9.6,我认为它应该存在于此处...?)。

我想象它应该有效的示例代码:

from typing import List, Annotated, MaxLen

def function(foo: Annotated[List[int], MaxLen(10)]):
    # ...
    return True
Run Code Online (Sandbox Code Playgroud)

哪里可以找到MaxLen

编辑:

看起来MaxLen你必须创建某种类。问题是我不知道你应该怎么做。有公开的例子吗?有人如何实现这个功能?

python type-hinting python-typing python-3.9

10
推荐指数
1
解决办法
3073
查看次数

以哨兵值作为默认值的类型提示参数

目前,当我无法在函数签名中分配默认参数和/或已经具有含义时,我会使用此策略。None

from typing import Optional

DEFAULT = object()


# `None` already has meaning.
def spam(ham: Optional[list[str]] = DEFAULT):
    if ham is DEFAULT:
        ham = ['prosciutto', 'jamon']
    if ham is None:
        print('Eggs?')
    else:
        print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)

错误:

Failed (exit code: 1) (2607 ms)

main.py:7: error: Incompatible default for argument "ham" (default has type "object", argument has type "Optional[List[str]]")
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
  • 如何在 mypy 中输入提示ham而不出现错误?或者
  • 我应该使用什么策略来代替DEFAULT = object() …

python type-hinting mypy python-typing python-3.9

10
推荐指数
2
解决办法
1478
查看次数

如何在运行时检查 TypeVar 的类型

我有一个通用类Graph[Generic[T], object]
我的问题是,是否有任何函数返回作为泛型传递给类的类型Graph

>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
Run Code Online (Sandbox Code Playgroud)

python generics static-typing python-typing

9
推荐指数
1
解决办法
5521
查看次数

Python 3.9.1 中的 collections.abc.Callable 是否有 bug?

Python 3.9包括PEP 585并弃用了模块中的许多类型,typing转而支持 中的类型collections.abc,现在它们支持__class_getitem__. 例如,就是这种情况Callable。对我来说,似乎typing.Callablecollections.abc.Callable应该总是表现得相似,但事实并非如此。

这个简单的示例会导致错误:

>>> from typing import Optional
>>> from collections.abc import Callable
>>> def foo(arg: Optional[Callable[[int], int]]) -> None:
...    pass
...
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/local/lib/python3.9/typing.py", line 262, in inner
    return func(*args, **kwds)
  File "/usr/local/lib/python3.9/typing.py", line 339, in __getitem__
    return self._getitem(self, parameters)
  File "/usr/local/lib/python3.9/typing.py", line 463, in Optional
    return Union[arg, type(None)]
  File …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-collections python-typing python-3.9

9
推荐指数
1
解决办法
3933
查看次数