You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
open(cloud_path) acts on cached local file instead of cloud file #128
Unfortunately the following code does not behave as expected:
withopen(cloud_path, "w") asfp:
fp.write("foo")
(as opposed to using cloud_path.open("w") which does work as expected).
What will happen is that this will only modify the local cached copy of the file without uploading it to the cloud. Then further attempts to interact with the cloud path will correctly raise OverwriteNewerLocal exceptions. Because cloud paths have an __fspath__ method (#72) that returns the local file path, the open function will only interact with that local file path.
Users can still get the correct behavior by using the open method. However, I've seen a lot of people using regular pathlib, especially those who are still new to it, with open(path, "w") on their Path objects, so I expect this may be a common pattern for users of cloudpathlib as well.
The gist of the problem here is that our os.PathLike support fails in write situations.
Because CloudPath implements __fspath__ and therefore the os.PathLike protocol, it can be accepted by anything that supports an os.PathLike input, which will call __fspath__ and do whatever with the returned filepath. This fine and dandy for read operations, because the local cache file's path is returned and the caller will read that file, and we have the ability to refresh the cache before that happens.
However, the problem happens when the caller writes. We're able to refresh the cache within __fspath__ before returning the local cache's path, but after we return, we're out of that method's scope and can't do anything else. The caller will write to the local cache, but we won't be able to sync the cache back up to the cloud.
This may be impossible to fix. Once __fspath__ returns, we won't be able to do anything. We'd really like __fspath__ to behave like a context manager so we can run some code after, but unfortunately we can't actually do that because the os.PathLike protocol requires __fspath__ to return bytes or str. We'd need the Python standard library to implement a protocol that supports a context manager and then they have to convince all of the other libraries to support their new context manager interface. os.PathLike has been out since Python 3.6 and there are still lots of places that don't support it yet and still only support filepaths as strings.
If it's the case that this is impossible to fix, then we have two options:
1. Keep our os.PathLike support but try to detect when it's being used in a write case so we can raise an exception.
@pjbull suggested that we could maybe use the inspect module to trace the callstack. We could potentially try to detect if it's being used by the built-in open function and then check whether mode is set to one of the writable ones.
It's not clear to me we can come up with a solution that is guaranteed to catch all cases though. If some user calls __fspath__, stores the content as a string, and then writes to that file later, that would be harder to reliably detect. I'm also not sure if the builtins open is the only way you can write to files in Python or not.
2. Remove __fspath__ and don't implement the os.PathLike interface.
That means users can't pass cloud paths into functions that expect os.PathLike inputs, even for reading.
I think (1) is probably worth doing, and that we also may add a section to the docs on writing to the cloud so that we can be very explicit about what we recommend, when you might see errors, and how it could be fixed. Probably with having a library level setting for making this a warning/error.
Here are two other ideas while we're brainstorming:
3. Patch open
I would not do this by default, but I could see having a CLOUDPATHLIB_OVERRIDE_OPEN env var that is documented and could be set. If it is set at import time, we override the open builtin (and maybe also os.open?) With our own version that does the write-mode check (only adds the one check for read scenarios, so shouldn't be a huge perf hit). If we are in write mode, we supply our own object that will upload on __exit__/.close().
I guess the primary use case here is if you have large/complex code bases that you want to pass CloudPath objects into, but don't want to change all of the open calls in the existing code.
4. Warn/raise on del if cache file has changed.
We track modified-time of the cache file at the object level. In __del__, if the on-disk modified time is greater than the one on the object, we can warn or raise.
I could also see an env var here that would enable uploading to the cloud in __del__ if the local cache is newer, but that seems high risk for foot-shooting.
Hi @grisaitis. This is indeed another case of the problem documented by this issue—cloud paths do not support being directly called with third-party functions (like pd.to_parquet(cloud_path)) that generically do writes. Unfortunately, we are not close to being able to support it. Most of the discussion related to this issue involves giving users a clearer error to indicate that this is not supported.
This introduces local paths that you need to define and manage. It is also not the most efficient, because it introduces another copy of the data that uses up disk space, as well as associated extra reads/writes.
(2): Use as_uri() to leverage other cloud filesystem libraries, like fsspec. This only works if the function you're passing cloud_path.as_uri() into has some other third-party support and if you have those dependencies installed. It works for pandas because pandas supports fsspec. What happens in this case is that you're using cloudpathlib to potentially manipulate paths (using a pathlib-like syntax) but using an fsspec backend (s3fs, gcsfs, etc.), which is an entirely independent library, for the actual write to the cloud.
Good news! @pjbull pointed out to me another option, which is probably the best for cases that support it.
(0): For write functions that support getting file objects/handles as inputs, you can using cloud_path.open("w"). pandas does indeed support this. The syntax here is a little clunky but it has the advantage over the other two options of not involving an extra copy of the file and leveraging purely cloudpathlib on the backend.
You could start an asynchronous file watcher (eg in a thread) that detects changes whenever __fspath__ is called. It would have to know when the changes come from cloupath vs externally
Whoa, I don't think I've considered that usage pattern. Thanks @FullMetalMeowchemist! It's really interesting that that works, given that we didn't (I don't think, anyways) do it intentionally. I think it makes sense, given that CloudPath.open patches the returned context manager to upload the local file to the cloud.
@pjbull I'm wondering if we do something like: on calls to fspath, check whether we have a buffer context manager active, and error if not? Then we could potentially enforce the pattern of
withcloud_path.open():
whatever_write(cloud_path)
and error if fspath is called without being inside the context manager.
I guess it may still be undesirably cumbersome for read cases though to require a context manager, and this doesn't help with detecting the difference between read and write usage.
Whoa, I don't think I've considered that usage pattern. Thanks @FullMetalMeowchemist! It's really interesting that that works, given that we didn't (I don't think, anyways) do it intentionally. I think it makes sense, given that CloudPath.open patches the returned context manager to upload the local file to the cloud.
@jayqi it sounds then like there isn't much difference between (continuing the previous example for objects with write methods that don't accept a file handle but only a file name):
@jayqi it sounds then like there isn't much difference between (continuing the previous example for objects with write methods that don't accept a file handle but only a file name):
... would there be any technical reasons to prefer one over the other? Thanks
There aren't any huge differences in this single operation.
However, if you later need to read the file you just uploaded, you may be able to save a download using the first approach. This is because first approach will create a cloudpathlib-managed local cache file, whereas your second approach explicitly manages its own temporary file. A later read operation would compare the cloudpathlib local cache file to the cloud file and would skip a download if it determines the cache is up-to-date. The second approach wouldn't have a local cache file and so it will always download to create one.
Activity
jayqi commentedon Mar 7, 2021
The gist of the problem here is that our
os.PathLikesupport fails in write situations.Because
CloudPathimplements__fspath__and therefore theos.PathLikeprotocol, it can be accepted by anything that supports anos.PathLikeinput, which will call__fspath__and do whatever with the returned filepath. This fine and dandy for read operations, because the local cache file's path is returned and the caller will read that file, and we have the ability to refresh the cache before that happens.However, the problem happens when the caller writes. We're able to refresh the cache within
__fspath__before returning the local cache's path, but after we return, we're out of that method's scope and can't do anything else. The caller will write to the local cache, but we won't be able to sync the cache back up to the cloud.This may be impossible to fix. Once
__fspath__returns, we won't be able to do anything. We'd really like__fspath__to behave like a context manager so we can run some code after, but unfortunately we can't actually do that because theos.PathLikeprotocol requires__fspath__to returnbytesorstr. We'd need the Python standard library to implement a protocol that supports a context manager and then they have to convince all of the other libraries to support their new context manager interface.os.PathLikehas been out since Python 3.6 and there are still lots of places that don't support it yet and still only support filepaths as strings.If it's the case that this is impossible to fix, then we have two options:
1. Keep our
os.PathLikesupport but try to detect when it's being used in a write case so we can raise an exception.@pjbull suggested that we could maybe use the
inspectmodule to trace the callstack. We could potentially try to detect if it's being used by the built-inopenfunction and then check whethermodeis set to one of the writable ones.It's not clear to me we can come up with a solution that is guaranteed to catch all cases though. If some user calls
__fspath__, stores the content as a string, and then writes to that file later, that would be harder to reliably detect. I'm also not sure if the builtinsopenis the only way you can write to files in Python or not.2. Remove
__fspath__and don't implement theos.PathLikeinterface.That means users can't pass cloud paths into functions that expect
os.PathLikeinputs, even for reading.pjbull commentedon Mar 13, 2021
I think (1) is probably worth doing, and that we also may add a section to the docs on writing to the cloud so that we can be very explicit about what we recommend, when you might see errors, and how it could be fixed. Probably with having a library level setting for making this a warning/error.
Here are two other ideas while we're brainstorming:
3. Patch
openI would not do this by default, but I could see having a
CLOUDPATHLIB_OVERRIDE_OPENenv var that is documented and could be set. If it is set at import time, we override theopenbuiltin (and maybe alsoos.open?) With our own version that does the write-mode check (only adds the one check for read scenarios, so shouldn't be a huge perf hit). If we are in write mode, we supply our own object that will upload on__exit__/.close().I guess the primary use case here is if you have large/complex code bases that you want to pass
CloudPathobjects into, but don't want to change all of theopencalls in the existing code.4. Warn/raise on del if cache file has changed.
We track modified-time of the cache file at the object level. In
__del__, if the on-disk modified time is greater than the one on the object, we can warn or raise.I could also see an env var here that would enable uploading to the cloud in
__del__if the local cache is newer, but that seems high risk for foot-shooting.grisaitis commentedon Sep 15, 2022
Hi! I'm encountering this issue in a context similar to #240, with pandas.
This issue causes a problem with
pandas.DataFrame.to_*(path), where you can't write to the same file more than once :/Example:
jayqi commentedon Sep 15, 2022
Hi @grisaitis. This is indeed another case of the problem documented by this issue—cloud paths do not support being directly called with third-party functions (like
pd.to_parquet(cloud_path)) that generically do writes. Unfortunately, we are not close to being able to support it. Most of the discussion related to this issue involves giving users a clearer error to indicate that this is not supported.grisaitis commentedon Sep 15, 2022
@jayqi thank you so much for the reply.
should i be calling
str(cloud_path)orcloud_path.to_uri()?jayqi commentedon Sep 15, 2022
@grisaitis there are
twothree directions of workarounds you can take:Update: See best option (0) in the following comment
(1): Introduce explicit local file paths and then use cloudpathlib to write/upload to the cloud. Some example pseudo-code:
This introduces local paths that you need to define and manage. It is also not the most efficient, because it introduces another copy of the data that uses up disk space, as well as associated extra reads/writes.
(2): Use
as_uri()to leverage other cloud filesystem libraries, like fsspec. This only works if the function you're passingcloud_path.as_uri()into has some other third-party support and if you have those dependencies installed. It works for pandas because pandas supports fsspec. What happens in this case is that you're using cloudpathlib to potentially manipulate paths (using a pathlib-like syntax) but using an fsspec backend (s3fs, gcsfs, etc.), which is an entirely independent library, for the actual write to the cloud.jayqi commentedon Sep 15, 2022
Good news! @pjbull pointed out to me another option, which is probably the best for cases that support it.
(0): For write functions that support getting file objects/handles as inputs, you can using
cloud_path.open("w"). pandas does indeed support this. The syntax here is a little clunky but it has the advantage over the other two options of not involving an extra copy of the file and leveraging purely cloudpathlib on the backend.See example:
Created at 2022-09-15 16:53:55 EDT by reprexlite v0.5.0
@grisaitis
grisaitis commentedon Sep 15, 2022
Thanks!
Since I want to avoid having any extra clutter around just calling
df.to_*(path), I might try out https://github.com/fsspec/universal_pathlib as wellEpicWink commentedon Sep 20, 2022
You could start an asynchronous file watcher (eg in a thread) that detects changes whenever
__fspath__is called. It would have to know when the changes come from cloupath vs externallybarneygale commentedon Nov 27, 2022
Related issue in the standard library: python/cpython#99818
FullMetalMeowchemist commentedon Nov 3, 2023
Another work around I've found is to use the context manage to open the CloudPath and do the write operation as normal.
I'm working with
pyarrow.parquet, and thewrite_tablemethod only accepts astrorpyarrow.NativeFile. This is the example I've ended up withjayqi commentedon Nov 5, 2023
Whoa, I don't think I've considered that usage pattern. Thanks @FullMetalMeowchemist! It's really interesting that that works, given that we didn't (I don't think, anyways) do it intentionally. I think it makes sense, given that
CloudPath.openpatches the returned context manager to upload the local file to the cloud.@pjbull I'm wondering if we do something like: on calls to
fspath, check whether we have a buffer context manager active, and error if not? Then we could potentially enforce the pattern ofand error if
fspathis called without being inside the context manager.I guess it may still be undesirably cumbersome for read cases though to require a context manager, and this doesn't help with detecting the difference between read and write usage.
ollie-bell commentedon Jul 1, 2024
@jayqi it sounds then like there isn't much difference between (continuing the previous example for objects with write methods that don't accept a file handle but only a file name):
and something like
... would there be any technical reasons to prefer one over the other? Thanks
jayqi commentedon Jul 1, 2024
There aren't any huge differences in this single operation.
However, if you later need to read the file you just uploaded, you may be able to save a download using the first approach. This is because first approach will create a cloudpathlib-managed local cache file, whereas your second approach explicitly manages its own temporary file. A later read operation would compare the cloudpathlib local cache file to the cloud file and would skip a download if it determines the cache is up-to-date. The second approach wouldn't have a local cache file and so it will always download to create one.
pjbull commentedon Sep 28, 2025
There is still an underlying issue here, but this can be worked around by patching the builtins:
https://cloudpathlib.drivendata.org/stable/patching_builtins/
For example: