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
rasterio.open typing updates #11
base: master
Are you sure you want to change the base?
Conversation
@@ -30,7 +46,7 @@ def open( | |||
nodata: Nodata | None = ..., | |||
sharing: bool = ..., | |||
**kwargs | |||
) -> Union[DatasetReader, DatasetWriter]: ... | |||
) -> DatasetReader: ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does this work? Usually you need an overload for each discriminator, and then a fallback, but maybe it works a little differently in stub files.
@overload
def open(
fp,
mode: str = "w",
...
) -> DatasetWriter: ...
@overload
def open(
fp,
mode: str = "r",
...
) -> DatasetReader: ...
def open(
fp,
mode: str = ...,
...
) -> Union[DatasetReader, DatasetWriter]: ...
For example, does rasterio support anything other than w
and r
? Does it support an append mode?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good question, I was just getting it going for my use case and then figured I'd share the change. I'll take a look and update it to be more comprehensive.
def __enter__(self, *args, **kwargs) -> DatasetReader: ... | ||
def __exit__(self, *args, **kwargs): ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These don't exist in the rasterio implementation of DatasetReader
: https://github.com/rasterio/rasterio/blob/38ad052cc2ab460d0b632bd2f3d7919e3d96c3c8/rasterio/io.py#L28-L34
Ideally they'd be put on DatasetBase
:
https://github.com/rasterio/rasterio/blob/38ad052cc2ab460d0b632bd2f3d7919e3d96c3c8/rasterio/_base.pyx#L436-L441
Offering two improvements to the open() type stub:
The DatasetReader and DatasetWriter stubs should support context manager ("with _ as _") syntax, achieved through the
__enter__
and__exit__
methods.Union[DatasetReader, DatasetWriter]
is not quite the correct return type because it restricts usage to only methods contained in both classes. Instead, I overloaded the stub to return either a DatasetReader or DatasetWriter conditionally based on themode
parameter. This also results in more accurate type hinting.