Skip to content

Commit

Permalink
Make CloudPath.is_valid_cloudpath a TypeGuard
Browse files Browse the repository at this point in the history
This allows us to infer that CloudPaths are the same type of object as the class is_valid_cloudpath is called on
  • Loading branch information
ringohoffman committed Jun 9, 2023
1 parent 4211d49 commit fe48641
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion cloudpathlib/cloudpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
from urllib.parse import urlparse
from warnings import warn

if sys.version_info >= (3, 10):
from typing import TypeGuard
else:
from typing_extensions import TypeGuard
if sys.version_info >= (3, 11):
from typing import Self
else:
Expand Down Expand Up @@ -258,8 +262,20 @@ def _no_prefix(self) -> str:
def _no_prefix_no_drive(self) -> str:
return self._str[len(self.cloud_prefix) + len(self.drive) :]

@overload
@classmethod
def is_valid_cloudpath(cls, path: "CloudPath", raise_on_error: bool = ...) -> TypeGuard[Self]:
...

Check warning on line 268 in cloudpathlib/cloudpath.py

View check run for this annotation

Codecov / codecov/patch

cloudpathlib/cloudpath.py#L268

Added line #L268 was not covered by tests

@overload
@classmethod
def is_valid_cloudpath(cls, path: str, raise_on_error: bool = ...) -> bool:
...

Check warning on line 273 in cloudpathlib/cloudpath.py

View check run for this annotation

Codecov / codecov/patch

cloudpathlib/cloudpath.py#L273

Added line #L273 was not covered by tests

@classmethod
def is_valid_cloudpath(cls, path: Union[str, "CloudPath"], raise_on_error=False) -> bool:
def is_valid_cloudpath(
cls, path: Union[str, "CloudPath"], raise_on_error: bool = False
) -> Union[bool, TypeGuard[Self]]:
valid = str(path).lower().startswith(cls.cloud_prefix.lower())

if raise_on_error and not valid:
Expand Down

0 comments on commit fe48641

Please sign in to comment.