【问题标题】:How do I type "requests" when it's a function argument?当它是函数参数时,如何输入“请求”?
【发布时间】:2021-09-18 08:50:51
【问题描述】:

Python 3.9,mypi 0.910。

假设我有一些代码可以让你传入一些可以生成 http 获取/发布的东西,但如果你不这样做,则回退到旧的 requests 库。我可能已经为测试做了这个,所以我可以很容易地传入一个存根。

import requests

def something(request_client = None):
  if not request_client:
    request_client = requests

  request_client.get('https://example.com')
  [...]

requests_client 的适当类型提示是什么?

【问题讨论】:

  • 仅供参考,如果您有一个默认为 None 的参数,最好使用 if request_client is None 而不是 if not request_client

标签: python python-3.x type-hinting


【解决方案1】:

联合或者如果您的自定义类继承自请求,您可以只使用该类本身。

如果你想要union

request_client:Union[my_class,request]=None

或python 3.10

    request_client:my_class|request=None

【讨论】:

  • 我可能脑子里放了个屁。是不是像 ``` from requests import request [...] def something(requests_client: request = None) ``` ?因为 mypy 说的是Function "requests.api.request" is not valid as a typeModule has no attribute "post"。如果只是import requests 请求,则显示Module "requests" is not valid as a type
  • @JB - 专门针对当前的模块,您唯一的选择是ModuleType
【解决方案2】:

您编写的函数不接受函数参数,而是接受模块参数。我建议让它实际上接受一个函数参数,因为这使得键入 测试/模拟更容易:

import requests
from typing import Callable

Getter = Callable[[str], requests.models.Response]


def something(get: Getter = requests.get) -> None:
    get('https://example.com')

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多