小编onl*_*egg的帖子

python3中pytest的布局和导入

我无法从pytest函数导入模块。我知道有100万个问题,但是我已经读了一堆,但仍然难以理解。

$ tree
.
??? code
    ??? eight_puzzle.py
    ??? missionaries_and_cannibals.py
    ??? node.py
    ??? search.py
    ??? test
        ??? test_eight_puzzle.py
        ??? test_search.py

2 directories, 6 files
$
$ grep import code/test/test_search.py
import sys
import pytest
import code.search
$
$ pytest
...
ImportError while importing test module '~/Documents/code/test/test_search.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
code/test/test_search.py:14: in <module>
    import code.search
E   ModuleNotFoundError: No module named 'code.search'; 'code' is not a package
...
Run Code Online (Sandbox Code Playgroud)

我希望那能奏效。“代码”是一个包,对吗?Python 3中的软件包是其中包含.py文件的任何目录。

我也尝试了相对导入-- from .. import search …

python pytest python-3.x conda

8
推荐指数
1
解决办法
1226
查看次数

带有 asynccontextmanager 的 Python 抽象方法

我有几个速率限制器类(其中一个未显示),我想为其创建 ABC。该request方法是一个异步上下文管理器。通过下面显示的代码我得到

“请求”的签名与超类型“RateLimiterInterface”不兼容

如果我尝试用 装饰抽象方法@asynccontextmanager,则会出现输入错误:

“asynccontextmanager”的参数 1 具有不兼容的类型“Callable[[RateLimiterInterface], Coroutine[Any, Any, AsyncIterator[Any]]]”;预期“Callable[...,AsyncIterator[]]”

我怎样才能做到这一点?

class RateLimiterInterface(abc.ABC):
    @abc.abstractmethod
    async def request(self) -> AsyncIterator:
        pass

class LeakyBucketRateLimiter(RateLimiterInterface):
    def __init__(self, max_tokens: Optional[int] = None, rate: float = 60) -> None:
        self.max_tokens = max_tokens
        self.rate = rate
        self._bucket = max_tokens
        self._last_added_at = time.time()

    @contextlib.asynccontextmanager
    async def request(self) -> AsyncIterator:
        if self._bucket is None:
            yield
            return
        while not self._bucket:
            await asyncio.sleep(0)
            self._add_tokens(int((time.time() - self._last_added_at) * self.rate))
        self._bucket -= 1
        yield
        return

    def _add_tokens(self, …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-asyncio mypy

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

标签 统计

python ×2

python-3.x ×2

conda ×1

mypy ×1

pytest ×1

python-asyncio ×1