Skip to content
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

pathlib __truediv__ returns the "self" type #553

Closed
dckc opened this issue Sep 17, 2016 · 3 comments
Closed

pathlib __truediv__ returns the "self" type #553

dckc opened this issue Sep 17, 2016 · 3 comments

Comments

@dckc
Copy link

dckc commented Sep 17, 2016

The pathlib implementation seems to go to some trouble to preserve subtypes in children. This works fine:

import pathlib


class MyPath(pathlib.PosixPath):
    def parity(self):
        return len(str(self)) % 2

root = MyPath('/')
print(root.parity())
child = root / 'there'
print(child.parity())
$ python3 t.py 
1
0

But this declaration isn't parameterized:

    def __truediv__(self, key: Union[str, PurePath]) -> PurePath: ...

so the program above doesn't typecheck:

$ mypy t.py 
t.py:11: error: "PurePath" has no attribute "parity"
@gvanrossum
Copy link
Member

Yes, this is currently a problem. We first need to solve python/mypy#1212 and then it should be easy. See also python/peps#89

@dckc
Copy link
Author

dckc commented Sep 17, 2016

I found a work-around:

import pathlib as pl
from typing import TypeVar, Generic, Union


Self = TypeVar('Self')


class PosixPathFix(pl.PosixPath, Generic[Self]):
    def __truediv__(self, key: Union [str, pl.PurePath]) -> Self:   # type: ignore
        return super(PosixPathFix, self).__truediv__(key)  # type: ignore


class MyPath(PosixPathFix):
    def parity(self):
        return len(str(self)) % 2


root = MyPath('/')
print(root, root.parity())
child = root / 'there'
print(child, child.parity())

@gvanrossum
Copy link
Member

gvanrossum commented Sep 17, 2016 via email

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

2 participants