Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
petsuter opened this issue Jun 27, 2019 · 2 comments

Comments

@petsuter
Copy link

I have this code which was accepted in a older version (0.6xx?) of mypy:

import pathlib
import shutil
from typing import Union

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

But is not accepted by mypy 0.710:

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

How should I fix my type annotations?
I tried this:

import os
import shutil
from typing import TypeVar

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

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

And that seems to work.


I asked this on StackOverflow but it was suggested to open a "bug/missing feature issue" here.

@Michael0x2a
Copy link
Collaborator

Michael0x2a commented Jun 27, 2019

More specifically, I think the root cause is that we don't properly perform union math on functions containing TypeVars with value restrictions:

from typing import TypeVar, Union

T = TypeVar('T', int, str)

def test(x: T) -> T:
    return x

y: Union[int, str]
test(y)

We get a Value of type variable "T" of "test" cannot be "Union[int, str]" error on the final line, which I think is suboptimal -- test is morally equivalent to an overload, and we'd accept a call of test(Union[int, str]) if the signature was written as such.

(Note that shutil.copyfile(...) accepts a TypeVar with value restriction for the second arg, and fails when passed a union.)

...it's a little surprising to me that we don't have an issue for this already, actually. I tried searching for one before suggesting OP file an issue here, but no dice.

@ilevkivskyi
Copy link
Member

Duplicate of #1533

@ilevkivskyi ilevkivskyi marked this as a duplicate of #1533 Jun 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants