cloudpathlib: Pyright type checking does not pass (causing Pylance in vscode to show typing errors)

For example I need to use str() for .stem field, otherwise it shows:

image

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 16 (14 by maintainers)

Most upvoted comments

@karolzlot, a few thoughts here from looking at your example in https://github.com/microsoft/pyright/issues/4896:

First, as @pjbull said, S3Path intentionally does not accept any CloudPath object as an argument—it should only work with S3Path. I think you actually intend something like:

cloud_path: Union[str, S3Path]

However, this will still result in a type error from pyright, because super().__init__ is expecting cloud_path: Union[str, S3PathWrapper]. As was correctly explained in this comment in the other thread, the inherited super().__init__ is designed only to expect objects of the self type.

It may be possible that we could change S3Path to explicitly initialize from instances of S3Path rather than a self class. That would mean subclasses would in general inherit an __init__ that takes S3Path, like what you are doing. However, I’m not convinced this is a sensible change to make—in general, I would expect more often that subclasses add more behavior that would be missing from the parent S3Path and so it wouldn’t make sense to be able to initialize from S3Path.

I don’t know much about what you’re trying to accomplish since you’ve only shared a minimal example with the interface. However, the fact that you named your class “Wrapper” suggests that subclassing isn’t the best approach. You may want a different implementation that stores an instance of S3Path as an attribute (that actually wraps S3Path).

I would type hint properties normally and for _dispatch_to_path just do,

def _dispatch_to_path(self, func: str, *args: object, **kwargs: object) -> Any:
    ...

dispatch_to_path is doing too much magic to be understandable for a static type checker. Mostly getattribute and how literal string value of func can change return type in a variety of ways. After you effectively ignore _dispatch_to_path you can add hints for each property normally like,

@property
def name(self) -> str:
    ...