小编duf*_*f18的帖子

Mypy:得到“函数”,预期为“Callable[...,Any]”

import glob
from typing import Callable, List


def fun1(b: str) -> List[str]:
    return ["a", "b"] + [b]


def fun(a: str) -> Callable:
    return fun1 if a == "hello" else glob.glob
Run Code Online (Sandbox Code Playgroud)

在此文件上运行 mypy 会给出:

error: Incompatible return value type (got "function", expected "Callable[..., Any]")  [return-value]
Run Code Online (Sandbox Code Playgroud)

但我认为函数是可调用的?这似乎是特定的,glob.glob因为如果我简单地返回fun1,那么错误就会消失。

编辑

在 github 上打开了一个问题

python mypy python-typing

7
推荐指数
1
解决办法
2717
查看次数

在字符串格式中调用类方法

考虑一下:

from datetime import datetime

now = datetime.now() 
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22

'{0.strftime("%p")}'.format(now)
# gives
# AttributeError: 'datetime.datetime' object has no attribute 'strftime("%p")'

Run Code Online (Sandbox Code Playgroud)

这似乎意味着我不能在格式中调用类方法(我猜strftime就是这样)。

对此有什么解决方法(假设我需要在字符串中调用方法,并继续使用格式)?

python string format

5
推荐指数
1
解决办法
462
查看次数

标签 统计

python ×2

format ×1

mypy ×1

python-typing ×1

string ×1