小编san*_*ers的帖子

将异步函数作为函数参数的 Python 类型提示

我试图确保函数参数是异步函数。所以我在玩以下代码:

async def test(*args, **kwargs):
    pass

def consumer(function_: Optional[Coroutine[Any, Any, Any]]=None):
    func = function_

consumer(test)
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

在 pyCharm 中进行类型检查时出现以下错误:

Expected type 'Optional[Coroutine]', got '(args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Coroutine[Any, Any, None]' instead
Run Code Online (Sandbox Code Playgroud)

谁能给我一些提示如何解决这个问题?

python type-hinting pycharm python-asyncio

12
推荐指数
2
解决办法
8691
查看次数

打开 Path 对象时的 Pycharm 类型提示警告

使用以下代码:

from pathlib import Path

file = Path("test.txt")

with open(file) as fl:
    pass 
Run Code Online (Sandbox Code Playgroud)

Pycharm 给出以下警告 file

Unexpected type(s): (Path) 

Possible types: 
  (Union[str, bytes, int]) 
  (Union[str, bytes, int, PathLike]) less... (Ctrl+F1) 

Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations.
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么 ?

python type-hinting pycharm

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

__init__ 类中的 TypeVar 类型提示

我试图使用 TypeVar 来指示 init 参数为某种类型。但我做错了,或者根本不可能。

from typing import TypeVar

T=TypeVar("T")

class TestClass:
    def __init__(self,value:T):
        self._value=value

a = TestClass(value=10)
b = TestClass(value="abc")

reveal_type(a._value)
reveal_type(b._value)
Run Code Online (Sandbox Code Playgroud)

我希望揭露类型a._value会是int并且b._value一直是string。但它们都显示为“T`-1”

任何帮助或见解表示赞赏!

[编辑]

稍微扩展一点的例子。BaseClass 将被覆盖,实际类型提示由覆盖类提供。

from typing import TypeVar

T=TypeVar("T")

class BaseClass:
    def __init__(self,value):
        self._value = value

class Class1(BaseClass):
    def __init__(self,value:str):
        super().__init__(value)

class Class2(BaseClass):
    def __init__(self,value:int):
        super().__init__(value)

a = Class1("A value")
b = Class2(10)

reveal_type(a._value)
reveal_type(b._value)
Run Code Online (Sandbox Code Playgroud)

python python-typing

6
推荐指数
1
解决办法
4707
查看次数

Websocket 连接的 Pytest 测试

使用 aiohttp 进行客户端请求和 websocket 连接我试图找到一个合适的 pytest 实现。

对于客户端请求,我使用aioresponses https://pypi.python.org/pypi/aioresponses/0.1.2

为了模拟 websocket 连接,我不知道该怎么做。有人有什么建议吗?

谢谢 !

python pytest aiohttp

4
推荐指数
1
解决办法
4652
查看次数