Skip to content

pathlib __truediv__ returns the "self" type #553

Closed

Description

@dckc

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"

Activity

  1. gvanrossum commented on Sep 17, 2016

    @gvanrossum
    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

  2. dckc commented on Sep 17, 2016

    @dckc
    Author

    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())
  3. gvanrossum commented on Sep 17, 2016

    @gvanrossum
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions