Check for major version of Python package

PHOTO EMBED

Fri Jan 24 2025 02:00:51 GMT+0000 (Coordinated Universal Time)

Saved by @ktyle #python

try:
    package = "zarr"
    package_version = version(package)
    major_version = int(package_version.split(".")[0])  # Extract the major version
    if major_version == 3:
        print(f"The package major version is {major_version}.")
        import zarr
        import fsspec
        # strip leading 's3://' from url
        url1 = url1[5:]
        url2 = url2[5:]
        fs = fsspec.filesystem("s3", asynchronous=True)
        store1 = zarr.storage.FsspecStore(fs, path=url1)
        store2 = zarr.storage.FsspecStore(fs, path=url2)
        file1 = zarr.open(store=store1)
        file2 = zarr.open(store=store2)
    else:
        print(f"The package major version is {major_version}.")
        import s3fs
        fs = s3fs.S3FileSystem(anon=True)
        file1 = s3fs.S3Map(url1, s3=fs)
        file2 = s3fs.S3Map(url2, s3=fs)
        
except PackageNotFoundError:
    print(f"{package} is not installed")
content_copyCOPY

Used to test for Zarr v2/v3, since behavior for opening S3 objects changed (see https://github.com/zarr-developers/zarr-python/issues/2706 and https://github.com/zarr-developers/zarr-python/issues/2748) Code block partially from ChatGPT