首页 > 解决方案 > mypy 错误:“copyfile”的类型变量“_AnyPath”的值不能是“Union [str, Path]”

问题描述

这曾经适用于 mypy 的旧版本(0.6xx?):

import pathlib
import shutil
from typing import Union

def f(x: Union[str, pathlib.Path]):
    shutil.copyfile("bla", x)

但不是在它抱怨的 mypy 0.710 中:

error: Value of type variable "_AnyPath" of "copyfile" cannot be "Union[str, Path]"

应该如何修复?

标签: pythonmypy

解决方案


这似乎是唯一的方法:

import os
import shutil
from typing import TypeVar

_AnyPath = TypeVar("_AnyPath", str, os.PathLike)

def f(x: _AnyPath):
    shutil.copyfile("bla", x)

推荐阅读