相关疑难解决方法(0)

嵌套字典的类型提示

在我的Python脚本的一种数据结构我分析的是一个JSON文件,该文件后json.load(file_handle),是类型<class 'dict'>。到现在为止还挺好。现在对于使用它作为输入参数的函数,我想要解析的 json 的类型提示。我在打字文档中读到,对于dicts 作为参数,我应该使用Mapping[key_type, value_type]

from typing import Mapping

def foo(json_data: Mapping[str, str]) -> None:
    ...
Run Code Online (Sandbox Code Playgroud)

我解析的 json 有str-type 键和str-type 值,但通常情况下,它的结构是高度递归的。因此,值更可能是dict带有str键的 a,甚至是dicts 作为值。它是非常嵌套的,直到在最深的层次上,最后一个 dict 终于有了str键和str值。

那么我如何更精确地表示这个数据结构呢?我在想一些事情,沿着这个问题的思路,它可能是:

Union[Mapping[str, str], Mapping[str, Mapping]]
Run Code Online (Sandbox Code Playgroud)

但它似乎只代表一级递归。有没有更好的方法来提示这个?

python json dictionary type-hinting

7
推荐指数
2
解决办法
2833
查看次数

如何在 Python 中键入提示嵌套对象?

我目前正在与 WSDL 进行集成,因此决定使用 Zeep 库与 Python 一起使用。

我正在尝试使用 对响应进行建模mypy,以便它可以与 VSCode 的 Intellisense 配合使用,并且在我进行粗心的分配或修改时也会给我一些提示。但是,当 WSDL 响应位于嵌套对象中时,我遇到了障碍,而且我无法找到对其进行类型提示的方法。

来自 WSDL 的示例响应:

{
    'result': {
        'code': '1',
        'description': 'Success',
        'errorUUID': None
    },
    'accounts': {
        'accounts': [
            {
                'accountId': 1,
                'accountName': 'Ming',
                'availableCredit': 1
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用以下代码段进行类型提示:

{
    'result': {
        'code': '1',
        'description': 'Success',
        'errorUUID': None
    },
    'accounts': {
        'accounts': [
            {
                'accountId': 1,
                'accountName': 'Ming',
                'availableCredit': 1
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

对于尝试 1,原因很明显。但是在尝试了尝试 2 之后,我不知道如何继续了。我在这里缺少什么?

更新:按照@Avi Kaminetzky 的回答,我尝试了以下( …

python type-hinting python-3.x mypy zeep

7
推荐指数
2
解决办法
2529
查看次数

在Python中定义递归类型提示?

假设我有一个接受a Garthok,an Iterable[Garthok],an Iterable[Iterable[Garthok]]等的函数。

def narfle_the_garthoks(arg):
  if isinstance(arg, Iterable):
    for value in arg:
       narfle(arg)
  else:
    arg.narfle()
Run Code Online (Sandbox Code Playgroud)

有什么方法可以为arg指定类型提示,以指示它接受Iterables中Garthoks的任何级别?我怀疑不是,但以为我会检查我是否缺少某些东西。

解决方法是,我仅指定几个级别,然后以结尾Iterable[Any]

Union[Garthok,
    Iterable[Union[Garthok,
        Iterable[Union[Garthok, 
            Iterable[Union[Garthok, Iterable[Any]]]]]]]]
Run Code Online (Sandbox Code Playgroud)

type-hinting python-3.x

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

递归类型注解

我正在尝试在适用的情况下向我的代码库引入静态类型注释。一种情况是在读取 JSON 时,结果对象将是一个以字符串为键的字典,具有以下类型之一的值:

  • bool
  • str
  • float
  • int
  • list
  • dict

然而listdict以上可以包含相同类型的字典,导致递归定义。这在 Python3 的类型结构中可以表示吗?

python typing python-3.x

3
推荐指数
2
解决办法
2381
查看次数

标签 统计

python ×3

python-3.x ×3

type-hinting ×3

dictionary ×1

json ×1

mypy ×1

typing ×1

zeep ×1