相关疑难解决方法(0)

如何使用类型提示指定多个返回类型

我在python中有一个函数可以返回a bool或a list.有没有办法使用类型提示指定返回类型.

例如,这是正确的方法吗?

def foo(id) -> list or bool:
      ...
Run Code Online (Sandbox Code Playgroud)

python return-type type-hinting python-3.x python-3.5

141
推荐指数
4
解决办法
4万
查看次数

Python 中可变嵌套 Dict 的类型提示

由于我在 Python 中经常使用类型提示,因此我遇到了递归函数接受dict,str作为键和intdict作为值 ( Dict[str, Union[int, Dict[...]]) 的场景。此时的问题是可能的dict-value 也有str作为键和intdict作为值 ( Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]])。

但是,我不知道传递的字典有什么深度。是否有可能通过类型提示来可视化这种重复模式?

python type-hinting python-typing

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

加载 YAML 文件后添加类型提示的正确方法是什么?

我正在向我的 Python 代码添加类型提示,并且想知道对加载的 YAML 文件进行类型提示的正确方法是什么,因为它是任意数量字典的字典。

有没有比类型提示更好的方法返回加载的 YAML 文件Dict[str, Dict[str, Any]]

这是函数:

def load_yaml(yaml_in: str) -> Dict[str, Dict[str, Any]]:
    return yaml.load(open(yaml_in), Loader=yaml.FullLoader)
Run Code Online (Sandbox Code Playgroud)

以下是正在加载的 YAML 文件的示例:

VariableMap:
    var1: 'time'
    var2: 'param_name'

GlobalVariables:
    limits:
        x-min:
        x-max:
        y-min:
        y-max:

Plots:
    plot1:
        file: 
        x_data: 'date'
        y_data: [{param: 'param1', label: "param1", color: 'red', linestyle: '-'},
                 {param: 'param2', label: "param2", color: 'black', linestyle: '--'}]
        labels:
            title: {label: 'title', fontsize: '9'}
            x-axis: {xlabel: 'x-label', fontsize: '9'}
            y-axis: {ylabel: 'y-label', fontsize: '9'}
        limits:
            x-min: 0
            x-max: 100 …
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x

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