Package: transparentpath
StatusCompatibilitiesThis package is not maintained for python 3.6 anymore. The latest version available for python 3.6 is 0.1.129.
It should work on Python 3.7, even though it is not tested with it. Please use python == 3.8. Python 3.9 and above
fail to create the tar.gz.ContactTransparentPathA class that allows one to use a path in a local file system or a Google Cloud Storage (GCS) file system in the
same way one would use apathlib.Pathobject. One can use many different GCP projects at once.RequirementsYou will need GCP credentials, either as a.jsonfile, that you can set in the envvar GOOGLE_APPLICATION_CREDENTIALS, or
by running directly in a google cloud instance (VM, pods, etc...).InstallationYou can install this package with pip :pipinstalltransparentpathOptional packagesThe vanilla version allows you to declare paths and work with them. You can use them in the builtinopenmethod.
Optionally, you can also install support for several other packages like pandas, dask, etc... the currently
available optionnal packages are accessible through the follownig commands:pipinstalltransparentpath[pandas]pipinstalltransparentpath[parquet]pipinstalltransparentpath[hdf5]pipinstalltransparentpath[json]pipinstalltransparentpath[excel]pipinstalltransparentpath[dask]you can install all of those at oncepipinstalltransparentpath[all]UsageCreate a path that points to GCS, and one that does not:fromtransparentpathimportPath# Or : from transparentpath import TransparentPathp=Path("gs://mybucket/some_path",token="some/cred/file.json")p2=p/"foo"# Will point to gs://mybucket/some_path/foop3=Path("bar")# Will point to local path "bar"Set all paths to point to GCS by default:fromtransparentpathimportPathPath.set_global_fs("gcs",token="some/cred/file.json")p=Path("mybucket")/"some_path"# Will point to gs://mybucket/some_pathp2=p/"foo"# Will point to gs://mybucket/some_path/foop3=Path("bar",fs="local")# Will point to local path "bar"p4=Path("other_bucket")# Will point to gs://other_bucket (assuming other_bucket is a bucket on GCS)p5=Path("not_a_bucket")# Will point to local path "not_a_bucket" (assuming it is indeed, not a bucket on GCS)Set all paths to point to severral GCS projects by default:fromtransparentpathimportPathPath.set_global_fs("gcs",token="some/cred/file.json")Path.set_global_fs("gcs",token="some/other/cred/file.json")p=Path("mybucket")/"some_path"# Will point to gs://mybucket/some_pathp2=p/"foo"# Will point to gs://mybucket/some_path/foop3=Path("bar",fs="local")# Will point to local path "bar"p4=Path("other_bucket")# Will point to gs://other_bucket (assuming other_bucket is a bucket on GCS)p5=Path("not_a_bucket")# Will point to local path "not_a_bucket" (assuming it is indeed, not a bucket on GCS)Here,mybucketandother_bucketcan be on two different projects, as long as at least one of the
credential files can access them.Set all paths to point to GCS by default, and specify a default bucket:fromtransparentpathimportPathPath.set_global_fs("gcs",bucket="mybucket",token="some/cred/file.json")p=Path("some_path")# Will point to gs://mybucket/some_path/p2=p/"foo"# Will point to gs://mybucket/some_path/foop3=Path("bar",fs="local")# Will point to local path "bar"p4=Path("other_bucket")# Will point to gs://mybucket/other_bucketp5=Path("not_a_bucket")# Will point to gs://mybucket/not_a_bucketThe latest option is interesting if you have a code that should be able to run with paths being sometimes remote, sometimes local.
To do that, you can use the class attributenas_dir. Then when a path is created, if it starts bynas_dir's path,nas_dir's path is replaced by the bucket name. This is useful if, for instance, you have a backup of a bucket locally at
let's say/my/local/backup. Then you can do:fromtransparentpathimportPathPath.nas_dir="/my/local/backup"Path.set_global_fs("gcs",bucket="mybucket",token="some/cred/file.json")p=Path("some_path")# Will point to gs://mybucket/some_path/p3=Path("/my/local/backup")/"some_path"# Will ALSO point to gs://mybucket/some_path/fromtransparentpathimportPathPath.nas_dir="/my/local/backup"# Path.set_global_fs("gcs", bucket="mybucket", token="some/cred/file.json")p=Path("some_path")# Will point to /my/local/backup/some_path/p3=Path("/my/local/backup")/"some_path"# Will ALSO point to /my/local/backup/some_path/In all the previous examples, thetokenargument can be ommited if the environment variableGOOGLE_APPLICATION_CREDENTIALSis set and point to a.jsoncredential file, or if your code runs on a GCP machine
(VM, cluster...) with access to GCS.No matter whether you are using GCS or your local file system, here is a sample of what TransparentPath can do:fromtransparentpathimportPath# Path.set_global_fs("gcs", bucket="bucket_name", project="project_name")# The following lines will also work with the previous line uncommented# Reading a csv into a pandas' DataFrame and saving it as a parquet filemypath=Path("foo")/"bar.csv"df=mypath.read(index_col=0,parse_dates=True)otherpath=mypath.with_suffix(".parquet")otherpath.write(df)# Reading and writing a HDF5 file works on GCS and on local:importnumpyasnpmypath=Path("foo")/"bar.hdf5"# can be .h5 toowithmypath.read()asifile:arr=np.array(ifile["store1"])# Doing '..' from 'foo/bar.hdf5' will return 'foo'# Then doing 'foo' + 'babar.hdf5' will return 'foo/babar.hdf5' ('+' and '/' are synonymes)mypath.cd("..")# Does not return a path but modifies inplacewith(mypath+"babar.hdf5").write(None)asofile:# Note here that we must explicitely give 'None' to the 'write' method in order for it# to return the open HDF5 file. We could also give a dict of {arr: "store1"} to directly# write the file.ofile["store1"]=arr# Reading a text file. Can also use 'w', 'a', etc... also works with binaries.mypath=Path("foo")/"bar.txt"withopen(mypath,"r")asifile:lines=ifile.readlines()# open is overriden to understand gs://withopen("gs://bucket/file.txt","r")asifile:lines=ifile.readlines()mypath.is_file()mypath.is_dir()mypath.is_file()files=mypath.parent.glob("*.csv")# Returns a Iterator[TransparentPath], can be casted to listAs you can see from the previous example, all methods returning a path from a TransparentPath return a
TransparentPath.DaskTransparentPath supports writing and reading Dask dataframes from and to csv, excel, parquet and HDF5, both locally and
remotely. You need to have dask-dataframe and dask-distributed installed, which will be the case if you ranpip  install transparentpath[dask]. Writing Dask dataframes does not require any additionnal arguments to be passed
for the type will be checked before calling the appropriate writting method. Reading however requires you to pass
theuse_daskargument to theread()method. If the file to read is HDF5, you will also need to specifyset_names, matching the argumentkeyof Dask'sread_hdf()method.Note that if reading a remote HDF5, the file will be downloaded in your local tmp, then read. If not using Dask, the
file is deleted after being read. But since Dask uses delayed processes, deleting the file might occure before the
file is actually read, so the file is kept. Up to you to empty your /tmp directory if it is not done automatically
by your system.BehaviorAll instances of TransparentPath are absolute, even if created with relative paths.TransparentPaths are seen as instances of str:fromtransparentpathimportPathpath=Path()isinstance(path,str)# returns TrueThis is required to allowfromtransparentpathimportPathpath=Path()withopen(path,"w/r/a/b...")asifile:...to work. If you want to check whether path is actually a TransparentPath and nothing else, usefromtransparentpathimportPathpath=Path()asserttype(path)==Pathassertissubclass(path,Path)instead.Any method or attribute valid in fsspec.implementations.local.LocalFileSystem, gcs.GCSFileSystem, pathlib.Path or str
can be used on a TransparentPath object.WarningsWarnings about GCS behaviourif you use GCS:Remember that directories are not a thing on GCS.You do not need the parent directories of a file on GCS to create the file : they will be created if they do not
exist (that is not true localy however).If you delete a file that was alone in its parent directories, those directories disapear.If a file exists at the same path than a directory, then TransparentPath is not able to know which one is the
file and which one is the directory, and will raise a TPMultipleExistenceError upon object creation. This
check for multiplicity is done at almost every method in case an exterior source created a duplicate of the
file/directory. This case can't happen locally. However, it can happen on remote if the cache is not updated
frequently. Doing this check can significantly increase computation time (if using glob on a directory
containing a lot of files for example). You can deactivate it either globally (TransparentPath._do_check =
False and TransparentPath._do_update_cache = False), for a specific path (pass nockeck=True at path
creation), or for glob and ls by passing fast=True as additional argument.SpeedTransparentPath on GCS is slow because of the verification for multiple existance and the cache updating.
However one can tweak those a bit. As mentionned earlier, cache updating and multiple existence check can be
deactivated for all paths by doingfromtransparentpathimportTransparentPathTransparentPath._do_update_cache=FalseTransparentPath._do_check=FalseThey can also be deactivated for one path only by doingp=TransparentPath("somepath",nocheck=True,notupdatecache=True)It is also possible to specify when to do those check : at path creation, path usage (read, write, exists...) or
both. Here to it can be set on all paths or only some :TransparentPath._when_checked={"created":True,"used":False}# Default valueTransparentPath._when_updated={"created":True,"used":False}# Default valuep=TransparentPath("somepath",when_checked={"created":False,"used":False},notupdatecache={"created":False,"used":False})There is also an expiration time in seconds for check and update : the operation is not done if it was done not a
long time ago. Those expiration times are of 1 second by default and can be changed through :TransparentPath._check_expire=10TransparentPath._update_expire=10p=TransparentPath("somepath",check_expire=0,update_expire=0)glob() and ls() have their own way to be accelerated :p.glob("/*",fast=True)p.ls("",fast=True)Basically,fast=Truemeans "do not check and do not update the cache" for all the items found by the method.builtin openBuiltinopen()is overloaded by TransparentPath to support giving a TransparentPath to it. If a method in a package you did
not create usesopen()in awithstatement, everything should work out of the box with a TransparentPath.However, if it uses theoutputofopen(), you will have to create a class to
override this method and anything using its ouput. Indeed,open()returns a file descriptor, not an IO, and I did
not find a way to access file descriptors on gcs. For example, in the FileLock package, theacquire()method calls the_acquire()method which callsos.open(), so I had to do that:fromfilelockimportFileLockfromtransparentpathimportTransparentPathasPathclassMyFileLock(FileLock):def_acquire(self):tmp_lock_file=self._lock_fileifnottype(tmp_lock_file)==Path:tmp_lock_file=Path(tmp_lock_file)try:fd=tmp_lock_file.open("x")except(IOError,OSError,FileExistsError):passelse:self._lock_file_fd=fdreturnNoneThe original method was:importos...def_acquire(self):open_mode=os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_TRUNCtry:fd=os.open(self._lock_file,open_mode)except(IOError,OSError):passelse:self._lock_file_fd=fdreturnNone...I tried to implement a working version of any method valid in pathlib.Path or in file systems, but futur changes
in any of those will not be taken into account quickly. You can report missing supports by opening an issue.