Skip to content

Group

zarr.Group dataclass

Bases: SyncMixin

A Zarr group.

Source code in zarr/core/group.py
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
@dataclass(frozen=True)
class Group(SyncMixin):
    """
    A Zarr group.
    """

    _async_group: AsyncGroup

    @classmethod
    def from_store(
        cls,
        store: StoreLike,
        *,
        attributes: dict[str, Any] | None = None,
        zarr_format: ZarrFormat = 3,
        overwrite: bool = False,
    ) -> Group:
        """Instantiate a group from an initialized store.

        Parameters
        ----------
        store : StoreLike
            StoreLike containing the Group.
        attributes : dict, optional
            A dictionary of JSON-serializable values with user-defined attributes.
        zarr_format : {2, 3}, optional
            Zarr storage format version.
        overwrite : bool, optional
            If True, do not raise an error if the group already exists.

        Returns
        -------
        Group
            Group instantiated from the store.

        Raises
        ------
        ContainsArrayError, ContainsGroupError, ContainsArrayAndGroupError
        """
        attributes = attributes or {}
        obj = sync(
            AsyncGroup.from_store(
                store,
                attributes=attributes,
                overwrite=overwrite,
                zarr_format=zarr_format,
            ),
        )

        return cls(obj)

    @classmethod
    def open(
        cls,
        store: StoreLike,
        zarr_format: ZarrFormat | None = 3,
    ) -> Group:
        """Open a group from an initialized store.

        Parameters
        ----------
        store : StoreLike
            Store containing the Group.
        zarr_format : {2, 3, None}, optional
            Zarr storage format version.

        Returns
        -------
        Group
            Group instantiated from the store.
        """
        obj = sync(AsyncGroup.open(store, zarr_format=zarr_format))
        return cls(obj)

    def __getitem__(self, path: str) -> Array | Group:
        """Obtain a group member.

        Parameters
        ----------
        path : str
            Group member name.

        Returns
        -------
        Array | Group
            Group member (Array or Group) at the specified key

        Examples
        --------
        >>> import zarr
        >>> group = Group.from_store(zarr.storage.MemoryStore()
        >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
        >>> group.create_group(name="subgroup").create_array(name="subarray", shape=(10,), chunks=(10,))
        >>> group["subarray"]
        <Array memory://132270269438272/subarray shape=(10,) dtype=float64>
        >>> group["subgroup"]
        <Group memory://132270269438272/subgroup>
        >>> group["subgroup"]["subarray"]
        <Array memory://132270269438272/subgroup/subarray shape=(10,) dtype=float64>

        """
        obj = self._sync(self._async_group.getitem(path))
        if isinstance(obj, AsyncArray):
            return Array(obj)
        else:
            return Group(obj)

    def get(self, path: str, default: DefaultT | None = None) -> Array | Group | DefaultT | None:
        """Obtain a group member, returning default if not found.

        Parameters
        ----------
        path : str
            Group member name.
        default : object
            Default value to return if key is not found (default: None).

        Returns
        -------
        object
            Group member (Array or Group) or default if not found.

        Examples
        --------
        >>> import zarr
        >>> group = Group.from_store(zarr.storage.MemoryStore()
        >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
        >>> group.create_group(name="subgroup")
        >>> group.get("subarray")
        <Array memory://132270269438272/subarray shape=(10,) dtype=float64>
        >>> group.get("subgroup")
        <Group memory://132270269438272/subgroup>
        >>> group.get("nonexistent", None)

        """
        try:
            return self[path]
        except KeyError:
            return default

    def __delitem__(self, key: str) -> None:
        """Delete a group member.

        Parameters
        ----------
        key : str
            Group member name.

        Examples
        --------
        >>> import zarr
        >>> group = Group.from_store(zarr.storage.MemoryStore()
        >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
        >>> del group["subarray"]
        >>> "subarray" in group
        False
        """
        self._sync(self._async_group.delitem(key))

    def __iter__(self) -> Iterator[str]:
        """Return an iterator over group member names.
        Examples
        --------
        >>> import zarr
        >>> g1 = zarr.group()
        >>> g2 = g1.create_group('foo')
        >>> g3 = g1.create_group('bar')
        >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
        >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
        >>> for name in g1:
        ...     print(name)
        baz
        bar
        foo
        quux
        """
        yield from self.keys()

    def __len__(self) -> int:
        """Number of members."""
        return self.nmembers()

    def __setitem__(self, key: str, value: Any) -> None:
        """Fastpath for creating a new array.

        New arrays will be created using default settings for the array type.
        If you need to create an array with custom settings, use the `create_array` method.

        Parameters
        ----------
        key : str
            Array name.
        value : Any
            Array data.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group["foo"] = zarr.zeros((10,))
        >>> group["foo"]
        <Array memory://132270269438272/foo shape=(10,) dtype=float64>
        """
        self._sync(self._async_group.setitem(key, value))

    def __repr__(self) -> str:
        return f"<Group {self.store_path}>"

    async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group:
        """Update the attributes of this group.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> await group.update_attributes_async({"foo": "bar"})
        >>> group.attrs.asdict()
        {'foo': 'bar'}
        """
        new_metadata = replace(self.metadata, attributes=new_attributes)

        # Write new metadata
        to_save = new_metadata.to_buffer_dict(default_buffer_prototype())
        awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()]
        await asyncio.gather(*awaitables)

        async_group = replace(self._async_group, metadata=new_metadata)
        return replace(self, _async_group=async_group)

    @property
    def store_path(self) -> StorePath:
        """Path-like interface for the Store."""
        return self._async_group.store_path

    @property
    def metadata(self) -> GroupMetadata:
        """Group metadata."""
        return self._async_group.metadata

    @property
    def path(self) -> str:
        """Storage path."""
        return self._async_group.path

    @property
    def name(self) -> str:
        """Group name following h5py convention."""
        return self._async_group.name

    @property
    def basename(self) -> str:
        """Final component of name."""
        return self._async_group.basename

    @property
    def attrs(self) -> Attributes:
        """Attributes of this Group"""
        return Attributes(self)

    @property
    def info(self) -> Any:
        """
        Return the statically known information for a group.

        Returns
        -------
        GroupInfo

        Related
        -------
        [zarr.Group.info_complete][]
            All information about a group, including dynamic information
            like the children members.
        """
        return self._async_group.info

    def info_complete(self) -> Any:
        """
        Return information for a group.

        If this group doesn't contain consolidated metadata then
        this will need to read from the backing Store.

        Returns
        -------
        GroupInfo

        Related
        -------
        [zarr.Group.info][]
        """
        return self._sync(self._async_group.info_complete())

    @property
    def store(self) -> Store:
        # Backwards compatibility for 2.x
        return self._async_group.store

    @property
    def read_only(self) -> bool:
        # Backwards compatibility for 2.x
        return self._async_group.read_only

    @property
    def synchronizer(self) -> None:
        # Backwards compatibility for 2.x
        # Not implemented in 3.x yet.
        return self._async_group.synchronizer

    def update_attributes(self, new_attributes: dict[str, Any]) -> Group:
        """Update the attributes of this group.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.update_attributes({"foo": "bar"})
        >>> group.attrs.asdict()
        {'foo': 'bar'}
        """
        self._sync(self._async_group.update_attributes(new_attributes))
        return self

    def nmembers(self, max_depth: int | None = 0) -> int:
        """Count the number of members in this group.

        Parameters
        ----------
        max_depth : int, default 0
            The maximum number of levels of the hierarchy to include. By
            default, (``max_depth=0``) only immediate children are included. Set
            ``max_depth=None`` to include all nodes, and some positive integer
            to consider children within that many levels of the root Group.

        Returns
        -------
        count : int
        """

        return self._sync(self._async_group.nmembers(max_depth=max_depth))

    def members(
        self, max_depth: int | None = 0, *, use_consolidated_for_children: bool = True
    ) -> tuple[tuple[str, Array | Group], ...]:
        """
        Returns an AsyncGenerator over the arrays and groups contained in this group.
        This method requires that `store_path.store` supports directory listing.

        The results are not guaranteed to be ordered.

        Parameters
        ----------
        max_depth : int, default 0
            The maximum number of levels of the hierarchy to include. By
            default, (``max_depth=0``) only immediate children are included. Set
            ``max_depth=None`` to include all nodes, and some positive integer
            to consider children within that many levels of the root Group.
        use_consolidated_for_children : bool, default True
            Whether to use the consolidated metadata of child groups loaded
            from the store. Note that this only affects groups loaded from the
            store. If the current Group already has consolidated metadata, it
            will always be used.

        Returns
        -------
        path:
            A string giving the path to the target, relative to the Group ``self``.
        value: AsyncArray or AsyncGroup
            The AsyncArray or AsyncGroup that is a child of ``self``.
        """
        _members = self._sync_iter(self._async_group.members(max_depth=max_depth))

        return tuple((kv[0], _parse_async_node(kv[1])) for kv in _members)

    def create_hierarchy(
        self,
        nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata],
        *,
        overwrite: bool = False,
    ) -> Iterator[tuple[str, Group | Array]]:
        """
        Create a hierarchy of arrays or groups rooted at this group.

        This function will parse its input to ensure that the hierarchy is complete. Any implicit groups
        will be inserted as needed. For example, an input like
        ```{'a/b': GroupMetadata}``` will be parsed to
        ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```.

        Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error
        because this group instance is the root group.

        After input parsing, this function then creates all the nodes in the hierarchy concurrently.

        Arrays and Groups are yielded in the order they are created. This order is not stable and
        should not be relied on.

        Parameters
        ----------
        nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]
            A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy,
            relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that
            all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the
            same hierarchy.

            Leading "/" characters from keys will be removed.
        overwrite : bool
            Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is
            raised instead of overwriting an existing array or group.

            This function will not erase an existing group unless that group is explicitly named in
            ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a
            group already exists at path ``a``, then this function will leave the group at ``a`` as-is.

        Yields
        ------
            tuple[str, Array | Group].

        Examples
        --------
        >>> import zarr
        >>> from zarr.core.group import GroupMetadata
        >>> root = zarr.create_group(store={})
        >>> for key, val in root.create_hierarchy({'a/b/c': GroupMetadata()}):
        ...   print(key, val)
        ...
        <AsyncGroup memory://123209880766144/a>
        <AsyncGroup memory://123209880766144/a/b/c>
        <AsyncGroup memory://123209880766144/a/b>
        """
        for key, node in self._sync_iter(
            self._async_group.create_hierarchy(nodes, overwrite=overwrite)
        ):
            yield (key, _parse_async_node(node))

    def keys(self) -> Generator[str, None]:
        """Return an iterator over group member names.

        Examples
        --------
        >>> import zarr
        >>> g1 = zarr.group()
        >>> g2 = g1.create_group('foo')
        >>> g3 = g1.create_group('bar')
        >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
        >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
        >>> for name in g1.keys():
        ...     print(name)
        baz
        bar
        foo
        quux
        """
        yield from self._sync_iter(self._async_group.keys())

    def __contains__(self, member: str) -> bool:
        """Test for group membership.

        Examples
        --------
        >>> import zarr
        >>> g1 = zarr.group()
        >>> g2 = g1.create_group('foo')
        >>> d1 = g1.create_array('bar', shape=(10,), chunks=(10,))
        >>> 'foo' in g1
        True
        >>> 'bar' in g1
        True
        >>> 'baz' in g1
        False

        """
        return self._sync(self._async_group.contains(member))

    def groups(self) -> Generator[tuple[str, Group], None]:
        """Return the sub-groups of this group as a generator of (name, group) pairs.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_group("subgroup")
        >>> for name, subgroup in group.groups():
        ...     print(name, subgroup)
        subgroup <Group memory://132270269438272/subgroup>
        """
        for name, async_group in self._sync_iter(self._async_group.groups()):
            yield name, Group(async_group)

    def group_keys(self) -> Generator[str, None]:
        """Return an iterator over group member names.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_group("subgroup")
        >>> for name in group.group_keys():
        ...     print(name)
        subgroup
        """
        for name, _ in self.groups():
            yield name

    def group_values(self) -> Generator[Group, None]:
        """Return an iterator over group members.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_group("subgroup")
        >>> for subgroup in group.group_values():
        ...     print(subgroup)
        <Group memory://132270269438272/subgroup>
        """
        for _, group in self.groups():
            yield group

    def arrays(self) -> Generator[tuple[str, Array], None]:
        """Return the sub-arrays of this group as a generator of (name, array) pairs

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_array("subarray", shape=(10,), chunks=(10,))
        >>> for name, subarray in group.arrays():
        ...     print(name, subarray)
        subarray <Array memory://140198565357056/subarray shape=(10,) dtype=float64>
        """
        for name, async_array in self._sync_iter(self._async_group.arrays()):
            yield name, Array(async_array)

    def array_keys(self) -> Generator[str, None]:
        """Return an iterator over group member names.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_array("subarray", shape=(10,), chunks=(10,))
        >>> for name in group.array_keys():
        ...     print(name)
        subarray
        """

        for name, _ in self.arrays():
            yield name

    def array_values(self) -> Generator[Array, None]:
        """Return an iterator over group members.

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> group.create_array("subarray", shape=(10,), chunks=(10,))
        >>> for subarray in group.array_values():
        ...     print(subarray)
        <Array memory://140198565357056/subarray shape=(10,) dtype=float64>
        """
        for _, array in self.arrays():
            yield array

    def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
        """
        Return a tree-like representation of a hierarchy.

        This requires the optional ``rich`` dependency.

        Parameters
        ----------
        expand : bool, optional
            This keyword is not yet supported. A NotImplementedError is raised if
            it's used.
        level : int, optional
            The maximum depth below this Group to display in the tree.

        Returns
        -------
        TreeRepr
            A pretty-printable object displaying the hierarchy.
        """
        return self._sync(self._async_group.tree(expand=expand, level=level))

    def create_group(self, name: str, **kwargs: Any) -> Group:
        """Create a sub-group.

        Parameters
        ----------
        name : str
            Name of the new subgroup.

        Returns
        -------
        Group

        Examples
        --------
        >>> import zarr
        >>> group = zarr.group()
        >>> subgroup = group.create_group("subgroup")
        >>> subgroup
        <Group memory://132270269438272/subgroup>
        """
        return Group(self._sync(self._async_group.create_group(name, **kwargs)))

    def require_group(self, name: str, **kwargs: Any) -> Group:
        """Obtain a sub-group, creating one if it doesn't exist.

        Parameters
        ----------
        name : str
            Group name.

        Returns
        -------
        g : Group
        """
        return Group(self._sync(self._async_group.require_group(name, **kwargs)))

    def require_groups(self, *names: str) -> tuple[Group, ...]:
        """Convenience method to require multiple groups in a single call.

        Parameters
        ----------
        *names : str
            Group names.

        Returns
        -------
        groups : tuple of Groups
        """
        return tuple(map(Group, self._sync(self._async_group.require_groups(*names))))

    def create(
        self,
        name: str,
        *,
        shape: ShapeLike | None = None,
        dtype: ZDTypeLike | None = None,
        data: np.ndarray[Any, np.dtype[Any]] | None = None,
        chunks: tuple[int, ...] | Literal["auto"] = "auto",
        shards: ShardsLike | None = None,
        filters: FiltersLike = "auto",
        compressors: CompressorsLike = "auto",
        compressor: CompressorLike = "auto",
        serializer: SerializerLike = "auto",
        fill_value: Any | None = DEFAULT_FILL_VALUE,
        order: MemoryOrder | None = None,
        attributes: dict[str, JSON] | None = None,
        chunk_key_encoding: ChunkKeyEncodingLike | None = None,
        dimension_names: DimensionNames = None,
        storage_options: dict[str, Any] | None = None,
        overwrite: bool = False,
        config: ArrayConfigLike | None = None,
        write_data: bool = True,
    ) -> Array:
        """Create an array within this group.

        This method lightly wraps [`zarr.core.array.create_array`][].

        Parameters
        ----------
        name : str
            The name of the array relative to the group. If ``path`` is ``None``, the array will be located
            at the root of the store.
        shape : ShapeLike, optional
            Shape of the array. Must be ``None`` if ``data`` is provided.
        dtype : npt.DTypeLike | None
            Data type of the array. Must be ``None`` if ``data`` is provided.
        data : Array-like data to use for initializing the array. If this parameter is provided, the
            ``shape`` and ``dtype`` parameters must be ``None``.
        chunks : tuple[int, ...], optional
            Chunk shape of the array.
            If not specified, default are guessed based on the shape and dtype.
        shards : tuple[int, ...], optional
            Shard shape of the array. The default value of ``None`` results in no sharding at all.
        filters : Iterable[Codec] | Literal["auto"], optional
            Iterable of filters to apply to each chunk of the array, in order, before serializing that
            chunk to bytes.

            For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
            and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
            dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

            For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
            the order if your filters is consistent with the behavior of each filter.

            The default value of ``"auto"`` instructs Zarr to use a default used based on the data
            type of the array and the Zarr format specified. For all data types in Zarr V3, and most
            data types in Zarr V2, the default filters are empty. The only cases where default filters
            are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
            [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
            the default filters contains a single element which is a codec specific to that particular data type.

            To create an array with no filters, provide an empty iterable or the value ``None``.
        compressors : Iterable[Codec], optional
            List of compressors to apply to the array. Compressors are applied in order, and after any
            filters are applied (if any are specified) and the data is serialized into bytes.

            For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
            returns another bytestream. Multiple compressors my be provided for Zarr format 3.
            If no ``compressors`` are provided, a default set of compressors will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_compressors``
            in [`zarr.config`][].
            Use ``None`` to omit default compressors.

            For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
            be provided for Zarr format 2.
            If no ``compressor`` is provided, a default compressor will be used.
            in [`zarr.config`][].
            Use ``None`` to omit the default compressor.
        compressor : Codec, optional
            Deprecated in favor of ``compressors``.
        serializer : dict[str, JSON] | ArrayBytesCodec, optional
            Array-to-bytes codec to use for encoding the array data.
            Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
            If no ``serializer`` is provided, a default serializer will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_serializer``
            in [`zarr.config`][].
        fill_value : Any, optional
            Fill value for the array.
        order : {"C", "F"}, optional
            The memory of the array (default is "C").
            For Zarr format 2, this parameter sets the memory order of the array.
            For Zarr format 3, this parameter is deprecated, because memory order
            is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
            order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
            If no ``order`` is provided, a default order will be used.
            This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][].
        attributes : dict, optional
            Attributes for the array.
        chunk_key_encoding : ChunkKeyEncoding, optional
            A specification of how the chunk keys are represented in storage.
            For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
            For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
        dimension_names : Iterable[str], optional
            The names of the dimensions (default is None).
            Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
        storage_options : dict, optional
            If using an fsspec URL to create the store, these will be passed to the backend implementation.
            Ignored otherwise.
        overwrite : bool, default False
            Whether to overwrite an array with the same name in the store, if one exists.
        config : ArrayConfig or ArrayConfigLike, optional
            Runtime configuration for the array.
        write_data : bool
            If a pre-existing array-like object was provided to this function via the ``data`` parameter
            then ``write_data`` determines whether the values in that array-like object should be
            written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
            array will be left empty.

        Returns
        -------
        AsyncArray
        """
        return self.create_array(
            name,
            shape=shape,
            dtype=dtype,
            data=data,
            chunks=chunks,
            shards=shards,
            filters=filters,
            compressors=compressors,
            compressor=compressor,
            serializer=serializer,
            fill_value=fill_value,
            order=order,
            attributes=attributes,
            chunk_key_encoding=chunk_key_encoding,
            dimension_names=dimension_names,
            storage_options=storage_options,
            overwrite=overwrite,
            config=config,
            write_data=write_data,
        )

    def create_array(
        self,
        name: str,
        *,
        shape: ShapeLike | None = None,
        dtype: ZDTypeLike | None = None,
        data: np.ndarray[Any, np.dtype[Any]] | None = None,
        chunks: tuple[int, ...] | Literal["auto"] = "auto",
        shards: ShardsLike | None = None,
        filters: FiltersLike = "auto",
        compressors: CompressorsLike = "auto",
        compressor: CompressorLike = "auto",
        serializer: SerializerLike = "auto",
        fill_value: Any | None = DEFAULT_FILL_VALUE,
        order: MemoryOrder | None = None,
        attributes: dict[str, JSON] | None = None,
        chunk_key_encoding: ChunkKeyEncodingLike | None = None,
        dimension_names: DimensionNames = None,
        storage_options: dict[str, Any] | None = None,
        overwrite: bool = False,
        config: ArrayConfigLike | None = None,
        write_data: bool = True,
    ) -> Array:
        """Create an array within this group.

        This method lightly wraps [zarr.core.array.create_array][].

        Parameters
        ----------
        name : str
            The name of the array relative to the group. If ``path`` is ``None``, the array will be located
            at the root of the store.
        shape : ShapeLike, optional
            Shape of the array. Must be ``None`` if ``data`` is provided.
        dtype : npt.DTypeLike | None
            Data type of the array. Must be ``None`` if ``data`` is provided.
        data : Array-like data to use for initializing the array. If this parameter is provided, the
            ``shape`` and ``dtype`` parameters must be ``None``.
        chunks : tuple[int, ...], optional
            Chunk shape of the array.
            If not specified, default are guessed based on the shape and dtype.
        shards : tuple[int, ...], optional
            Shard shape of the array. The default value of ``None`` results in no sharding at all.
        filters : Iterable[Codec] | Literal["auto"], optional
            Iterable of filters to apply to each chunk of the array, in order, before serializing that
            chunk to bytes.

            For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
            and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
            dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

            For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
            the order if your filters is consistent with the behavior of each filter.

            The default value of ``"auto"`` instructs Zarr to use a default used based on the data
            type of the array and the Zarr format specified. For all data types in Zarr V3, and most
            data types in Zarr V2, the default filters are empty. The only cases where default filters
            are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
            [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
            the default filters contains a single element which is a codec specific to that particular data type.

            To create an array with no filters, provide an empty iterable or the value ``None``.
        compressors : Iterable[Codec], optional
            List of compressors to apply to the array. Compressors are applied in order, and after any
            filters are applied (if any are specified) and the data is serialized into bytes.

            For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
            returns another bytestream. Multiple compressors my be provided for Zarr format 3.
            If no ``compressors`` are provided, a default set of compressors will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_compressors``
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit default compressors.

            For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
            be provided for Zarr format 2.
            If no ``compressor`` is provided, a default compressor will be used.
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit the default compressor.
        compressor : Codec, optional
            Deprecated in favor of ``compressors``.
        serializer : dict[str, JSON] | ArrayBytesCodec, optional
            Array-to-bytes codec to use for encoding the array data.
            Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
            If no ``serializer`` is provided, a default serializer will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_serializer``
            in [`zarr.config`][zarr.config].
        fill_value : Any, optional
            Fill value for the array.
        order : {"C", "F"}, optional
            The memory of the array (default is "C").
            For Zarr format 2, this parameter sets the memory order of the array.
            For Zarr format 3, this parameter is deprecated, because memory order
            is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
            order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
            If no ``order`` is provided, a default order will be used.
            This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
        attributes : dict, optional
            Attributes for the array.
        chunk_key_encoding : ChunkKeyEncoding, optional
            A specification of how the chunk keys are represented in storage.
            For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
            For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
        dimension_names : Iterable[str], optional
            The names of the dimensions (default is None).
            Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
        storage_options : dict, optional
            If using an fsspec URL to create the store, these will be passed to the backend implementation.
            Ignored otherwise.
        overwrite : bool, default False
            Whether to overwrite an array with the same name in the store, if one exists.
        config : ArrayConfig or ArrayConfigLike, optional
            Runtime configuration for the array.
        write_data : bool
            If a pre-existing array-like object was provided to this function via the ``data`` parameter
            then ``write_data`` determines whether the values in that array-like object should be
            written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
            array will be left empty.

        Returns
        -------
        AsyncArray
        """
        compressors = _parse_deprecated_compressor(
            compressor, compressors, zarr_format=self.metadata.zarr_format
        )
        return Array(
            self._sync(
                self._async_group.create_array(
                    name=name,
                    shape=shape,
                    dtype=dtype,
                    data=data,
                    chunks=chunks,
                    shards=shards,
                    fill_value=fill_value,
                    attributes=attributes,
                    chunk_key_encoding=chunk_key_encoding,
                    compressors=compressors,
                    serializer=serializer,
                    dimension_names=dimension_names,
                    order=order,
                    filters=filters,
                    overwrite=overwrite,
                    storage_options=storage_options,
                    config=config,
                    write_data=write_data,
                )
            )
        )

    @deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning)
    def create_dataset(self, name: str, **kwargs: Any) -> Array:
        """Create an array.

        !!! warning "Deprecated"
            `Group.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
            Use `Group.create_array` instead.


        Arrays are known as "datasets" in HDF5 terminology. For compatibility
        with h5py, Zarr groups also implement the [zarr.Group.require_dataset][] method.

        Parameters
        ----------
        name : str
            Array name.
        **kwargs : dict
            Additional arguments passed to [zarr.Group.create_array][]

        Returns
        -------
        a : Array
        """
        return Array(self._sync(self._async_group.create_dataset(name, **kwargs)))

    @deprecated("Use Group.require_array instead.", category=ZarrDeprecationWarning)
    def require_dataset(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> Array:
        """Obtain an array, creating if it doesn't exist.

        !!! warning "Deprecated"
            `Group.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
            Use `Group.require_array` instead.

        Arrays are known as "datasets" in HDF5 terminology. For compatibility
        with h5py, Zarr groups also implement the [zarr.Group.create_dataset][] method.

        Other `kwargs` are as per [zarr.Group.create_dataset][].

        Parameters
        ----------
        name : str
            Array name.
        **kwargs :
            See [zarr.Group.create_dataset][].

        Returns
        -------
        a : Array
        """
        return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs)))

    def require_array(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> Array:
        """Obtain an array, creating if it doesn't exist.

        Other `kwargs` are as per [zarr.Group.create_array][].

        Parameters
        ----------
        name : str
            Array name.
        **kwargs :
            See [zarr.Group.create_array][].

        Returns
        -------
        a : Array
        """
        return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs)))

    def empty(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
        """Create an empty array with the specified shape in this Group. The contents will be filled with
        the array's fill value or zeros if no fill value is provided.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Notes
        -----
        The contents of an empty Zarr array are not defined. On attempting to
        retrieve data from an empty Zarr array, any values may be returned,
        and these are not guaranteed to be stable from one access to the next.
        """
        return Array(self._sync(self._async_group.empty(name=name, shape=shape, **kwargs)))

    def zeros(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
        """Create an array, with zero being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """
        return Array(self._sync(self._async_group.zeros(name=name, shape=shape, **kwargs)))

    def ones(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
        """Create an array, with one being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """
        return Array(self._sync(self._async_group.ones(name=name, shape=shape, **kwargs)))

    def full(
        self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any
    ) -> Array:
        """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        fill_value : scalar
            Value to fill the array with.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """
        return Array(
            self._sync(
                self._async_group.full(name=name, shape=shape, fill_value=fill_value, **kwargs)
            )
        )

    def empty_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
        """Create an empty sub-array like `data`. The contents will be filled
        with the array's fill value or zeros if no fill value is provided.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create an empty array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.

        Notes
        -----
        The contents of an empty Zarr array are not defined. On attempting to
        retrieve data from an empty Zarr array, any values may be returned,
        and these are not guaranteed to be stable from one access to the next.
        """
        return Array(self._sync(self._async_group.empty_like(name=name, data=data, **kwargs)))

    def zeros_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
        """Create a sub-array of zeros like `data`.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """

        return Array(self._sync(self._async_group.zeros_like(name=name, data=data, **kwargs)))

    def ones_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
        """Create a sub-array of ones like `data`.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """
        return Array(self._sync(self._async_group.ones_like(name=name, data=data, **kwargs)))

    def full_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
        """Create a sub-array like `data` filled with the `fill_value` of `data` .

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        Array
            The new array.
        """
        return Array(self._sync(self._async_group.full_like(name=name, data=data, **kwargs)))

    def move(self, source: str, dest: str) -> None:
        """Move a sub-group or sub-array from one path to another.

        Notes
        -----
        Not implemented
        """
        return self._sync(self._async_group.move(source, dest))

    @deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning)
    def array(
        self,
        name: str,
        *,
        shape: ShapeLike,
        dtype: npt.DTypeLike,
        chunks: tuple[int, ...] | Literal["auto"] = "auto",
        shards: tuple[int, ...] | Literal["auto"] | None = None,
        filters: FiltersLike = "auto",
        compressors: CompressorsLike = "auto",
        compressor: CompressorLike = None,
        serializer: SerializerLike = "auto",
        fill_value: Any | None = DEFAULT_FILL_VALUE,
        order: MemoryOrder | None = None,
        attributes: dict[str, JSON] | None = None,
        chunk_key_encoding: ChunkKeyEncodingLike | None = None,
        dimension_names: DimensionNames = None,
        storage_options: dict[str, Any] | None = None,
        overwrite: bool = False,
        config: ArrayConfigLike | None = None,
        data: npt.ArrayLike | None = None,
    ) -> Array:
        """Create an array within this group.

        !!! warning "Deprecated"
            `Group.array()` is deprecated since v3.0.0 and will be removed in a future release.
            Use `Group.create_array` instead.

        This method lightly wraps [zarr.core.array.create_array][].

        Parameters
        ----------
        name : str
            The name of the array relative to the group. If ``path`` is ``None``, the array will be located
            at the root of the store.
        shape : tuple[int, ...]
            Shape of the array.
        dtype : npt.DTypeLike
            Data type of the array.
        chunks : tuple[int, ...], optional
            Chunk shape of the array.
            If not specified, default are guessed based on the shape and dtype.
        shards : tuple[int, ...], optional
            Shard shape of the array. The default value of ``None`` results in no sharding at all.
        filters : Iterable[Codec] | Literal["auto"], optional
            Iterable of filters to apply to each chunk of the array, in order, before serializing that
            chunk to bytes.

            For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
            and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
            dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

            For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
            the order if your filters is consistent with the behavior of each filter.

            The default value of ``"auto"`` instructs Zarr to use a default used based on the data
            type of the array and the Zarr format specified. For all data types in Zarr V3, and most
            data types in Zarr V2, the default filters are empty. The only cases where default filters
            are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
            [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
            the default filters contains a single element which is a codec specific to that particular data type.

            To create an array with no filters, provide an empty iterable or the value ``None``.
        compressors : Iterable[Codec], optional
            List of compressors to apply to the array. Compressors are applied in order, and after any
            filters are applied (if any are specified) and the data is serialized into bytes.

            For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
            returns another bytestream. Multiple compressors my be provided for Zarr format 3.
            If no ``compressors`` are provided, a default set of compressors will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_compressors``
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit default compressors.

            For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
            be provided for Zarr format 2.
            If no ``compressor`` is provided, a default compressor will be used.
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit the default compressor.
        compressor : Codec, optional
            Deprecated in favor of ``compressors``.
        serializer : dict[str, JSON] | ArrayBytesCodec, optional
            Array-to-bytes codec to use for encoding the array data.
            Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
            If no ``serializer`` is provided, a default serializer will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_serializer``
            in [`zarr.config`][zarr.config].
        fill_value : Any, optional
            Fill value for the array.
        order : {"C", "F"}, optional
            The memory of the array (default is "C").
            For Zarr format 2, this parameter sets the memory order of the array.
            For Zarr format 3, this parameter is deprecated, because memory order
            is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
            order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
            If no ``order`` is provided, a default order will be used.
            This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
        attributes : dict, optional
            Attributes for the array.
        chunk_key_encoding : ChunkKeyEncoding, optional
            A specification of how the chunk keys are represented in storage.
            For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
            For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
        dimension_names : Iterable[str], optional
            The names of the dimensions (default is None).
            Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
        storage_options : dict, optional
            If using an fsspec URL to create the store, these will be passed to the backend implementation.
            Ignored otherwise.
        overwrite : bool, default False
            Whether to overwrite an array with the same name in the store, if one exists.
        config : ArrayConfig or ArrayConfigLike, optional
            Runtime configuration for the array.
        data : array_like
            The data to fill the array with.

        Returns
        -------
        AsyncArray
        """
        compressors = _parse_deprecated_compressor(compressor, compressors)
        return Array(
            self._sync(
                self._async_group.create_dataset(
                    name=name,
                    shape=shape,
                    dtype=dtype,
                    chunks=chunks,
                    shards=shards,
                    fill_value=fill_value,
                    attributes=attributes,
                    chunk_key_encoding=chunk_key_encoding,
                    compressors=compressors,
                    serializer=serializer,
                    dimension_names=dimension_names,
                    order=order,
                    filters=filters,
                    overwrite=overwrite,
                    storage_options=storage_options,
                    config=config,
                    data=data,
                )
            )
        )

attrs property

attrs: Attributes

Attributes of this Group

basename property

basename: str

Final component of name.

info property

info: Any

Return the statically known information for a group.

Returns:

  • GroupInfo

metadata property

metadata: GroupMetadata

Group metadata.

name property

name: str

Group name following h5py convention.

path property

path: str

Storage path.

store_path property

store_path: StorePath

Path-like interface for the Store.

__contains__

__contains__(member: str) -> bool

Test for group membership.

Examples:

>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> d1 = g1.create_array('bar', shape=(10,), chunks=(10,))
>>> 'foo' in g1
True
>>> 'bar' in g1
True
>>> 'baz' in g1
False
Source code in zarr/core/group.py
def __contains__(self, member: str) -> bool:
    """Test for group membership.

    Examples
    --------
    >>> import zarr
    >>> g1 = zarr.group()
    >>> g2 = g1.create_group('foo')
    >>> d1 = g1.create_array('bar', shape=(10,), chunks=(10,))
    >>> 'foo' in g1
    True
    >>> 'bar' in g1
    True
    >>> 'baz' in g1
    False

    """
    return self._sync(self._async_group.contains(member))

__delitem__

__delitem__(key: str) -> None

Delete a group member.

Parameters:

  • key (str) –

    Group member name.

Examples:

>>> import zarr
>>> group = Group.from_store(zarr.storage.MemoryStore()
>>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
>>> del group["subarray"]
>>> "subarray" in group
False
Source code in zarr/core/group.py
def __delitem__(self, key: str) -> None:
    """Delete a group member.

    Parameters
    ----------
    key : str
        Group member name.

    Examples
    --------
    >>> import zarr
    >>> group = Group.from_store(zarr.storage.MemoryStore()
    >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
    >>> del group["subarray"]
    >>> "subarray" in group
    False
    """
    self._sync(self._async_group.delitem(key))

__getitem__

__getitem__(path: str) -> Array | Group

Obtain a group member.

Parameters:

  • path (str) –

    Group member name.

Returns:

  • Array | Group

    Group member (Array or Group) at the specified key

Examples:

>>> import zarr
>>> group = Group.from_store(zarr.storage.MemoryStore()
>>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
>>> group.create_group(name="subgroup").create_array(name="subarray", shape=(10,), chunks=(10,))
>>> group["subarray"]
<Array memory://132270269438272/subarray shape=(10,) dtype=float64>
>>> group["subgroup"]
<Group memory://132270269438272/subgroup>
>>> group["subgroup"]["subarray"]
<Array memory://132270269438272/subgroup/subarray shape=(10,) dtype=float64>
Source code in zarr/core/group.py
def __getitem__(self, path: str) -> Array | Group:
    """Obtain a group member.

    Parameters
    ----------
    path : str
        Group member name.

    Returns
    -------
    Array | Group
        Group member (Array or Group) at the specified key

    Examples
    --------
    >>> import zarr
    >>> group = Group.from_store(zarr.storage.MemoryStore()
    >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
    >>> group.create_group(name="subgroup").create_array(name="subarray", shape=(10,), chunks=(10,))
    >>> group["subarray"]
    <Array memory://132270269438272/subarray shape=(10,) dtype=float64>
    >>> group["subgroup"]
    <Group memory://132270269438272/subgroup>
    >>> group["subgroup"]["subarray"]
    <Array memory://132270269438272/subgroup/subarray shape=(10,) dtype=float64>

    """
    obj = self._sync(self._async_group.getitem(path))
    if isinstance(obj, AsyncArray):
        return Array(obj)
    else:
        return Group(obj)

__iter__

__iter__() -> Iterator[str]

Return an iterator over group member names.

Examples:

>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
>>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
>>> for name in g1:
...     print(name)
baz
bar
foo
quux
Source code in zarr/core/group.py
def __iter__(self) -> Iterator[str]:
    """Return an iterator over group member names.
    Examples
    --------
    >>> import zarr
    >>> g1 = zarr.group()
    >>> g2 = g1.create_group('foo')
    >>> g3 = g1.create_group('bar')
    >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
    >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
    >>> for name in g1:
    ...     print(name)
    baz
    bar
    foo
    quux
    """
    yield from self.keys()

__len__

__len__() -> int

Number of members.

Source code in zarr/core/group.py
def __len__(self) -> int:
    """Number of members."""
    return self.nmembers()

__setitem__

__setitem__(key: str, value: Any) -> None

Fastpath for creating a new array.

New arrays will be created using default settings for the array type. If you need to create an array with custom settings, use the create_array method.

Parameters:

  • key (str) –

    Array name.

  • value (Any) –

    Array data.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group["foo"] = zarr.zeros((10,))
>>> group["foo"]
<Array memory://132270269438272/foo shape=(10,) dtype=float64>
Source code in zarr/core/group.py
def __setitem__(self, key: str, value: Any) -> None:
    """Fastpath for creating a new array.

    New arrays will be created using default settings for the array type.
    If you need to create an array with custom settings, use the `create_array` method.

    Parameters
    ----------
    key : str
        Array name.
    value : Any
        Array data.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group["foo"] = zarr.zeros((10,))
    >>> group["foo"]
    <Array memory://132270269438272/foo shape=(10,) dtype=float64>
    """
    self._sync(self._async_group.setitem(key, value))

array

array(
    name: str,
    *,
    shape: ShapeLike,
    dtype: DTypeLike,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: tuple[int, ...] | Literal["auto"] | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = None,
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    data: ArrayLike | None = None,
) -> Array

Create an array within this group.

Deprecated

Group.array() is deprecated since v3.0.0 and will be removed in a future release. Use Group.create_array instead.

This method lightly wraps zarr.core.array.create_array.

Parameters:

  • name (str) –

    The name of the array relative to the group. If path is None, the array will be located at the root of the store.

  • shape (tuple[int, ...]) –

    Shape of the array.

  • dtype (DTypeLike) –

    Data type of the array.

  • chunks (tuple[int, ...], default: 'auto' ) –

    Chunk shape of the array. If not specified, default are guessed based on the shape and dtype.

  • shards (tuple[int, ...], default: None ) –

    Shard shape of the array. The default value of None results in no sharding at all.

  • filters (Iterable[Codec] | Literal['auto'], default: 'auto' ) –

    Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes.

    For Zarr format 3, a "filter" is a codec that takes an array and returns an array, and these values must be instances of zarr.abc.codec.ArrayArrayCodec, or a dict representations of zarr.abc.codec.ArrayArrayCodec.

    For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the the order if your filters is consistent with the behavior of each filter.

    The default value of "auto" instructs Zarr to use a default used based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like zarr.dtype.VariableLengthUTF8 or zarr.dtype.VariableLengthUTF8. In these cases, the default filters contains a single element which is a codec specific to that particular data type.

    To create an array with no filters, provide an empty iterable or the value None.

  • compressors (Iterable[Codec], default: 'auto' ) –

    List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes.

    For Zarr format 3, a "compressor" is a codec that takes a bytestream, and returns another bytestream. Multiple compressors my be provided for Zarr format 3. If no compressors are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of array.v3_default_compressors in zarr.config. Use None to omit default compressors.

    For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. If no compressor is provided, a default compressor will be used. in zarr.config. Use None to omit the default compressor.

  • compressor (Codec, default: None ) –

    Deprecated in favor of compressors.

  • serializer (dict[str, JSON] | ArrayBytesCodec, default: 'auto' ) –

    Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. If no serializer is provided, a default serializer will be used. These defaults can be changed by modifying the value of array.v3_default_serializer in zarr.config.

  • fill_value (Any, default: DEFAULT_FILL_VALUE ) –

    Fill value for the array.

  • order (('C', 'F'), default: "C" ) –

    The memory of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory order for Zarr format 3 arrays is via the config parameter, e.g. {'config': 'C'}. If no order is provided, a default order will be used. This default can be changed by modifying the value of array.order in zarr.config.

  • attributes (dict, default: None ) –

    Attributes for the array.

  • chunk_key_encoding (ChunkKeyEncoding, default: None ) –

    A specification of how the chunk keys are represented in storage. For Zarr format 3, the default is {"name": "default", "separator": "/"}}. For Zarr format 2, the default is {"name": "v2", "separator": "."}}.

  • dimension_names (Iterable[str], default: None ) –

    The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter.

  • storage_options (dict, default: None ) –

    If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise.

  • overwrite (bool, default: False ) –

    Whether to overwrite an array with the same name in the store, if one exists.

  • config (ArrayConfig or ArrayConfigLike, default: None ) –

    Runtime configuration for the array.

  • data (array_like, default: None ) –

    The data to fill the array with.

Returns:

Source code in zarr/core/group.py
@deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning)
def array(
    self,
    name: str,
    *,
    shape: ShapeLike,
    dtype: npt.DTypeLike,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: tuple[int, ...] | Literal["auto"] | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = None,
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    data: npt.ArrayLike | None = None,
) -> Array:
    """Create an array within this group.

    !!! warning "Deprecated"
        `Group.array()` is deprecated since v3.0.0 and will be removed in a future release.
        Use `Group.create_array` instead.

    This method lightly wraps [zarr.core.array.create_array][].

    Parameters
    ----------
    name : str
        The name of the array relative to the group. If ``path`` is ``None``, the array will be located
        at the root of the store.
    shape : tuple[int, ...]
        Shape of the array.
    dtype : npt.DTypeLike
        Data type of the array.
    chunks : tuple[int, ...], optional
        Chunk shape of the array.
        If not specified, default are guessed based on the shape and dtype.
    shards : tuple[int, ...], optional
        Shard shape of the array. The default value of ``None`` results in no sharding at all.
    filters : Iterable[Codec] | Literal["auto"], optional
        Iterable of filters to apply to each chunk of the array, in order, before serializing that
        chunk to bytes.

        For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
        and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
        dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

        For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
        the order if your filters is consistent with the behavior of each filter.

        The default value of ``"auto"`` instructs Zarr to use a default used based on the data
        type of the array and the Zarr format specified. For all data types in Zarr V3, and most
        data types in Zarr V2, the default filters are empty. The only cases where default filters
        are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
        [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
        the default filters contains a single element which is a codec specific to that particular data type.

        To create an array with no filters, provide an empty iterable or the value ``None``.
    compressors : Iterable[Codec], optional
        List of compressors to apply to the array. Compressors are applied in order, and after any
        filters are applied (if any are specified) and the data is serialized into bytes.

        For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
        returns another bytestream. Multiple compressors my be provided for Zarr format 3.
        If no ``compressors`` are provided, a default set of compressors will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_compressors``
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit default compressors.

        For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
        be provided for Zarr format 2.
        If no ``compressor`` is provided, a default compressor will be used.
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit the default compressor.
    compressor : Codec, optional
        Deprecated in favor of ``compressors``.
    serializer : dict[str, JSON] | ArrayBytesCodec, optional
        Array-to-bytes codec to use for encoding the array data.
        Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
        If no ``serializer`` is provided, a default serializer will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_serializer``
        in [`zarr.config`][zarr.config].
    fill_value : Any, optional
        Fill value for the array.
    order : {"C", "F"}, optional
        The memory of the array (default is "C").
        For Zarr format 2, this parameter sets the memory order of the array.
        For Zarr format 3, this parameter is deprecated, because memory order
        is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
        order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
        If no ``order`` is provided, a default order will be used.
        This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
    attributes : dict, optional
        Attributes for the array.
    chunk_key_encoding : ChunkKeyEncoding, optional
        A specification of how the chunk keys are represented in storage.
        For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
        For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
    dimension_names : Iterable[str], optional
        The names of the dimensions (default is None).
        Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
    storage_options : dict, optional
        If using an fsspec URL to create the store, these will be passed to the backend implementation.
        Ignored otherwise.
    overwrite : bool, default False
        Whether to overwrite an array with the same name in the store, if one exists.
    config : ArrayConfig or ArrayConfigLike, optional
        Runtime configuration for the array.
    data : array_like
        The data to fill the array with.

    Returns
    -------
    AsyncArray
    """
    compressors = _parse_deprecated_compressor(compressor, compressors)
    return Array(
        self._sync(
            self._async_group.create_dataset(
                name=name,
                shape=shape,
                dtype=dtype,
                chunks=chunks,
                shards=shards,
                fill_value=fill_value,
                attributes=attributes,
                chunk_key_encoding=chunk_key_encoding,
                compressors=compressors,
                serializer=serializer,
                dimension_names=dimension_names,
                order=order,
                filters=filters,
                overwrite=overwrite,
                storage_options=storage_options,
                config=config,
                data=data,
            )
        )
    )

array_keys

array_keys() -> Generator[str, None]

Return an iterator over group member names.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_array("subarray", shape=(10,), chunks=(10,))
>>> for name in group.array_keys():
...     print(name)
subarray
Source code in zarr/core/group.py
def array_keys(self) -> Generator[str, None]:
    """Return an iterator over group member names.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_array("subarray", shape=(10,), chunks=(10,))
    >>> for name in group.array_keys():
    ...     print(name)
    subarray
    """

    for name, _ in self.arrays():
        yield name

array_values

array_values() -> Generator[Array, None]

Return an iterator over group members.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_array("subarray", shape=(10,), chunks=(10,))
>>> for subarray in group.array_values():
...     print(subarray)
<Array memory://140198565357056/subarray shape=(10,) dtype=float64>
Source code in zarr/core/group.py
def array_values(self) -> Generator[Array, None]:
    """Return an iterator over group members.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_array("subarray", shape=(10,), chunks=(10,))
    >>> for subarray in group.array_values():
    ...     print(subarray)
    <Array memory://140198565357056/subarray shape=(10,) dtype=float64>
    """
    for _, array in self.arrays():
        yield array

arrays

arrays() -> Generator[tuple[str, Array], None]

Return the sub-arrays of this group as a generator of (name, array) pairs

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_array("subarray", shape=(10,), chunks=(10,))
>>> for name, subarray in group.arrays():
...     print(name, subarray)
subarray <Array memory://140198565357056/subarray shape=(10,) dtype=float64>
Source code in zarr/core/group.py
def arrays(self) -> Generator[tuple[str, Array], None]:
    """Return the sub-arrays of this group as a generator of (name, array) pairs

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_array("subarray", shape=(10,), chunks=(10,))
    >>> for name, subarray in group.arrays():
    ...     print(name, subarray)
    subarray <Array memory://140198565357056/subarray shape=(10,) dtype=float64>
    """
    for name, async_array in self._sync_iter(self._async_group.arrays()):
        yield name, Array(async_array)

create

create(
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: ndarray[Any, dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> Array

Create an array within this group.

This method lightly wraps zarr.core.array.create_array.

Parameters:

  • name (str) –

    The name of the array relative to the group. If path is None, the array will be located at the root of the store.

  • shape (ShapeLike, default: None ) –

    Shape of the array. Must be None if data is provided.

  • dtype (DTypeLike | None, default: None ) –

    Data type of the array. Must be None if data is provided.

  • data (Array-like data to use for initializing the array. If this parameter is provided, the, default: None ) –

    shape and dtype parameters must be None.

  • chunks (tuple[int, ...], default: 'auto' ) –

    Chunk shape of the array. If not specified, default are guessed based on the shape and dtype.

  • shards (tuple[int, ...], default: None ) –

    Shard shape of the array. The default value of None results in no sharding at all.

  • filters (Iterable[Codec] | Literal['auto'], default: 'auto' ) –

    Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes.

    For Zarr format 3, a "filter" is a codec that takes an array and returns an array, and these values must be instances of zarr.abc.codec.ArrayArrayCodec, or a dict representations of zarr.abc.codec.ArrayArrayCodec.

    For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the the order if your filters is consistent with the behavior of each filter.

    The default value of "auto" instructs Zarr to use a default used based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like zarr.dtype.VariableLengthUTF8 or zarr.dtype.VariableLengthUTF8. In these cases, the default filters contains a single element which is a codec specific to that particular data type.

    To create an array with no filters, provide an empty iterable or the value None.

  • compressors (Iterable[Codec], default: 'auto' ) –

    List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes.

    For Zarr format 3, a "compressor" is a codec that takes a bytestream, and returns another bytestream. Multiple compressors my be provided for Zarr format 3. If no compressors are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of array.v3_default_compressors in zarr.config. Use None to omit default compressors.

    For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. If no compressor is provided, a default compressor will be used. in zarr.config. Use None to omit the default compressor.

  • compressor (Codec, default: 'auto' ) –

    Deprecated in favor of compressors.

  • serializer (dict[str, JSON] | ArrayBytesCodec, default: 'auto' ) –

    Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. If no serializer is provided, a default serializer will be used. These defaults can be changed by modifying the value of array.v3_default_serializer in zarr.config.

  • fill_value (Any, default: DEFAULT_FILL_VALUE ) –

    Fill value for the array.

  • order (('C', 'F'), default: "C" ) –

    The memory of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory order for Zarr format 3 arrays is via the config parameter, e.g. {'config': 'C'}. If no order is provided, a default order will be used. This default can be changed by modifying the value of array.order in zarr.config.

  • attributes (dict, default: None ) –

    Attributes for the array.

  • chunk_key_encoding (ChunkKeyEncoding, default: None ) –

    A specification of how the chunk keys are represented in storage. For Zarr format 3, the default is {"name": "default", "separator": "/"}}. For Zarr format 2, the default is {"name": "v2", "separator": "."}}.

  • dimension_names (Iterable[str], default: None ) –

    The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter.

  • storage_options (dict, default: None ) –

    If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise.

  • overwrite (bool, default: False ) –

    Whether to overwrite an array with the same name in the store, if one exists.

  • config (ArrayConfig or ArrayConfigLike, default: None ) –

    Runtime configuration for the array.

  • write_data (bool, default: True ) –

    If a pre-existing array-like object was provided to this function via the data parameter then write_data determines whether the values in that array-like object should be written to the Zarr array created by this function. If write_data is False, then the array will be left empty.

Returns:

Source code in zarr/core/group.py
def create(
    self,
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: np.ndarray[Any, np.dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> Array:
    """Create an array within this group.

    This method lightly wraps [`zarr.core.array.create_array`][].

    Parameters
    ----------
    name : str
        The name of the array relative to the group. If ``path`` is ``None``, the array will be located
        at the root of the store.
    shape : ShapeLike, optional
        Shape of the array. Must be ``None`` if ``data`` is provided.
    dtype : npt.DTypeLike | None
        Data type of the array. Must be ``None`` if ``data`` is provided.
    data : Array-like data to use for initializing the array. If this parameter is provided, the
        ``shape`` and ``dtype`` parameters must be ``None``.
    chunks : tuple[int, ...], optional
        Chunk shape of the array.
        If not specified, default are guessed based on the shape and dtype.
    shards : tuple[int, ...], optional
        Shard shape of the array. The default value of ``None`` results in no sharding at all.
    filters : Iterable[Codec] | Literal["auto"], optional
        Iterable of filters to apply to each chunk of the array, in order, before serializing that
        chunk to bytes.

        For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
        and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
        dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

        For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
        the order if your filters is consistent with the behavior of each filter.

        The default value of ``"auto"`` instructs Zarr to use a default used based on the data
        type of the array and the Zarr format specified. For all data types in Zarr V3, and most
        data types in Zarr V2, the default filters are empty. The only cases where default filters
        are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
        [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
        the default filters contains a single element which is a codec specific to that particular data type.

        To create an array with no filters, provide an empty iterable or the value ``None``.
    compressors : Iterable[Codec], optional
        List of compressors to apply to the array. Compressors are applied in order, and after any
        filters are applied (if any are specified) and the data is serialized into bytes.

        For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
        returns another bytestream. Multiple compressors my be provided for Zarr format 3.
        If no ``compressors`` are provided, a default set of compressors will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_compressors``
        in [`zarr.config`][].
        Use ``None`` to omit default compressors.

        For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
        be provided for Zarr format 2.
        If no ``compressor`` is provided, a default compressor will be used.
        in [`zarr.config`][].
        Use ``None`` to omit the default compressor.
    compressor : Codec, optional
        Deprecated in favor of ``compressors``.
    serializer : dict[str, JSON] | ArrayBytesCodec, optional
        Array-to-bytes codec to use for encoding the array data.
        Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
        If no ``serializer`` is provided, a default serializer will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_serializer``
        in [`zarr.config`][].
    fill_value : Any, optional
        Fill value for the array.
    order : {"C", "F"}, optional
        The memory of the array (default is "C").
        For Zarr format 2, this parameter sets the memory order of the array.
        For Zarr format 3, this parameter is deprecated, because memory order
        is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
        order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
        If no ``order`` is provided, a default order will be used.
        This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][].
    attributes : dict, optional
        Attributes for the array.
    chunk_key_encoding : ChunkKeyEncoding, optional
        A specification of how the chunk keys are represented in storage.
        For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
        For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
    dimension_names : Iterable[str], optional
        The names of the dimensions (default is None).
        Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
    storage_options : dict, optional
        If using an fsspec URL to create the store, these will be passed to the backend implementation.
        Ignored otherwise.
    overwrite : bool, default False
        Whether to overwrite an array with the same name in the store, if one exists.
    config : ArrayConfig or ArrayConfigLike, optional
        Runtime configuration for the array.
    write_data : bool
        If a pre-existing array-like object was provided to this function via the ``data`` parameter
        then ``write_data`` determines whether the values in that array-like object should be
        written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
        array will be left empty.

    Returns
    -------
    AsyncArray
    """
    return self.create_array(
        name,
        shape=shape,
        dtype=dtype,
        data=data,
        chunks=chunks,
        shards=shards,
        filters=filters,
        compressors=compressors,
        compressor=compressor,
        serializer=serializer,
        fill_value=fill_value,
        order=order,
        attributes=attributes,
        chunk_key_encoding=chunk_key_encoding,
        dimension_names=dimension_names,
        storage_options=storage_options,
        overwrite=overwrite,
        config=config,
        write_data=write_data,
    )

create_array

create_array(
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: ndarray[Any, dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> Array

Create an array within this group.

This method lightly wraps zarr.core.array.create_array.

Parameters:

  • name (str) –

    The name of the array relative to the group. If path is None, the array will be located at the root of the store.

  • shape (ShapeLike, default: None ) –

    Shape of the array. Must be None if data is provided.

  • dtype (DTypeLike | None, default: None ) –

    Data type of the array. Must be None if data is provided.

  • data (Array-like data to use for initializing the array. If this parameter is provided, the, default: None ) –

    shape and dtype parameters must be None.

  • chunks (tuple[int, ...], default: 'auto' ) –

    Chunk shape of the array. If not specified, default are guessed based on the shape and dtype.

  • shards (tuple[int, ...], default: None ) –

    Shard shape of the array. The default value of None results in no sharding at all.

  • filters (Iterable[Codec] | Literal['auto'], default: 'auto' ) –

    Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes.

    For Zarr format 3, a "filter" is a codec that takes an array and returns an array, and these values must be instances of zarr.abc.codec.ArrayArrayCodec, or a dict representations of zarr.abc.codec.ArrayArrayCodec.

    For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the the order if your filters is consistent with the behavior of each filter.

    The default value of "auto" instructs Zarr to use a default used based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like zarr.dtype.VariableLengthUTF8 or zarr.dtype.VariableLengthUTF8. In these cases, the default filters contains a single element which is a codec specific to that particular data type.

    To create an array with no filters, provide an empty iterable or the value None.

  • compressors (Iterable[Codec], default: 'auto' ) –

    List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes.

    For Zarr format 3, a "compressor" is a codec that takes a bytestream, and returns another bytestream. Multiple compressors my be provided for Zarr format 3. If no compressors are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of array.v3_default_compressors in zarr.config. Use None to omit default compressors.

    For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. If no compressor is provided, a default compressor will be used. in zarr.config. Use None to omit the default compressor.

  • compressor (Codec, default: 'auto' ) –

    Deprecated in favor of compressors.

  • serializer (dict[str, JSON] | ArrayBytesCodec, default: 'auto' ) –

    Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. If no serializer is provided, a default serializer will be used. These defaults can be changed by modifying the value of array.v3_default_serializer in zarr.config.

  • fill_value (Any, default: DEFAULT_FILL_VALUE ) –

    Fill value for the array.

  • order (('C', 'F'), default: "C" ) –

    The memory of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory order for Zarr format 3 arrays is via the config parameter, e.g. {'config': 'C'}. If no order is provided, a default order will be used. This default can be changed by modifying the value of array.order in zarr.config.

  • attributes (dict, default: None ) –

    Attributes for the array.

  • chunk_key_encoding (ChunkKeyEncoding, default: None ) –

    A specification of how the chunk keys are represented in storage. For Zarr format 3, the default is {"name": "default", "separator": "/"}}. For Zarr format 2, the default is {"name": "v2", "separator": "."}}.

  • dimension_names (Iterable[str], default: None ) –

    The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter.

  • storage_options (dict, default: None ) –

    If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise.

  • overwrite (bool, default: False ) –

    Whether to overwrite an array with the same name in the store, if one exists.

  • config (ArrayConfig or ArrayConfigLike, default: None ) –

    Runtime configuration for the array.

  • write_data (bool, default: True ) –

    If a pre-existing array-like object was provided to this function via the data parameter then write_data determines whether the values in that array-like object should be written to the Zarr array created by this function. If write_data is False, then the array will be left empty.

Returns:

Source code in zarr/core/group.py
def create_array(
    self,
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: np.ndarray[Any, np.dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> Array:
    """Create an array within this group.

    This method lightly wraps [zarr.core.array.create_array][].

    Parameters
    ----------
    name : str
        The name of the array relative to the group. If ``path`` is ``None``, the array will be located
        at the root of the store.
    shape : ShapeLike, optional
        Shape of the array. Must be ``None`` if ``data`` is provided.
    dtype : npt.DTypeLike | None
        Data type of the array. Must be ``None`` if ``data`` is provided.
    data : Array-like data to use for initializing the array. If this parameter is provided, the
        ``shape`` and ``dtype`` parameters must be ``None``.
    chunks : tuple[int, ...], optional
        Chunk shape of the array.
        If not specified, default are guessed based on the shape and dtype.
    shards : tuple[int, ...], optional
        Shard shape of the array. The default value of ``None`` results in no sharding at all.
    filters : Iterable[Codec] | Literal["auto"], optional
        Iterable of filters to apply to each chunk of the array, in order, before serializing that
        chunk to bytes.

        For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
        and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
        dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

        For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
        the order if your filters is consistent with the behavior of each filter.

        The default value of ``"auto"`` instructs Zarr to use a default used based on the data
        type of the array and the Zarr format specified. For all data types in Zarr V3, and most
        data types in Zarr V2, the default filters are empty. The only cases where default filters
        are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
        [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
        the default filters contains a single element which is a codec specific to that particular data type.

        To create an array with no filters, provide an empty iterable or the value ``None``.
    compressors : Iterable[Codec], optional
        List of compressors to apply to the array. Compressors are applied in order, and after any
        filters are applied (if any are specified) and the data is serialized into bytes.

        For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
        returns another bytestream. Multiple compressors my be provided for Zarr format 3.
        If no ``compressors`` are provided, a default set of compressors will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_compressors``
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit default compressors.

        For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
        be provided for Zarr format 2.
        If no ``compressor`` is provided, a default compressor will be used.
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit the default compressor.
    compressor : Codec, optional
        Deprecated in favor of ``compressors``.
    serializer : dict[str, JSON] | ArrayBytesCodec, optional
        Array-to-bytes codec to use for encoding the array data.
        Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
        If no ``serializer`` is provided, a default serializer will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_serializer``
        in [`zarr.config`][zarr.config].
    fill_value : Any, optional
        Fill value for the array.
    order : {"C", "F"}, optional
        The memory of the array (default is "C").
        For Zarr format 2, this parameter sets the memory order of the array.
        For Zarr format 3, this parameter is deprecated, because memory order
        is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
        order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
        If no ``order`` is provided, a default order will be used.
        This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
    attributes : dict, optional
        Attributes for the array.
    chunk_key_encoding : ChunkKeyEncoding, optional
        A specification of how the chunk keys are represented in storage.
        For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
        For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
    dimension_names : Iterable[str], optional
        The names of the dimensions (default is None).
        Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
    storage_options : dict, optional
        If using an fsspec URL to create the store, these will be passed to the backend implementation.
        Ignored otherwise.
    overwrite : bool, default False
        Whether to overwrite an array with the same name in the store, if one exists.
    config : ArrayConfig or ArrayConfigLike, optional
        Runtime configuration for the array.
    write_data : bool
        If a pre-existing array-like object was provided to this function via the ``data`` parameter
        then ``write_data`` determines whether the values in that array-like object should be
        written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
        array will be left empty.

    Returns
    -------
    AsyncArray
    """
    compressors = _parse_deprecated_compressor(
        compressor, compressors, zarr_format=self.metadata.zarr_format
    )
    return Array(
        self._sync(
            self._async_group.create_array(
                name=name,
                shape=shape,
                dtype=dtype,
                data=data,
                chunks=chunks,
                shards=shards,
                fill_value=fill_value,
                attributes=attributes,
                chunk_key_encoding=chunk_key_encoding,
                compressors=compressors,
                serializer=serializer,
                dimension_names=dimension_names,
                order=order,
                filters=filters,
                overwrite=overwrite,
                storage_options=storage_options,
                config=config,
                write_data=write_data,
            )
        )
    )

create_dataset

create_dataset(name: str, **kwargs: Any) -> Array

Create an array.

Deprecated

Group.create_dataset() is deprecated since v3.0.0 and will be removed in v3.1.0. Use Group.create_array instead.

Arrays are known as "datasets" in HDF5 terminology. For compatibility with h5py, Zarr groups also implement the zarr.Group.require_dataset method.

Parameters:

Returns:

Source code in zarr/core/group.py
@deprecated("Use Group.create_array instead.", category=ZarrDeprecationWarning)
def create_dataset(self, name: str, **kwargs: Any) -> Array:
    """Create an array.

    !!! warning "Deprecated"
        `Group.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
        Use `Group.create_array` instead.


    Arrays are known as "datasets" in HDF5 terminology. For compatibility
    with h5py, Zarr groups also implement the [zarr.Group.require_dataset][] method.

    Parameters
    ----------
    name : str
        Array name.
    **kwargs : dict
        Additional arguments passed to [zarr.Group.create_array][]

    Returns
    -------
    a : Array
    """
    return Array(self._sync(self._async_group.create_dataset(name, **kwargs)))

create_group

create_group(name: str, **kwargs: Any) -> Group

Create a sub-group.

Parameters:

  • name (str) –

    Name of the new subgroup.

Returns:

Examples:

>>> import zarr
>>> group = zarr.group()
>>> subgroup = group.create_group("subgroup")
>>> subgroup
<Group memory://132270269438272/subgroup>
Source code in zarr/core/group.py
def create_group(self, name: str, **kwargs: Any) -> Group:
    """Create a sub-group.

    Parameters
    ----------
    name : str
        Name of the new subgroup.

    Returns
    -------
    Group

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> subgroup = group.create_group("subgroup")
    >>> subgroup
    <Group memory://132270269438272/subgroup>
    """
    return Group(self._sync(self._async_group.create_group(name, **kwargs)))

create_hierarchy

create_hierarchy(
    nodes: dict[
        str,
        ArrayV2Metadata | ArrayV3Metadata | GroupMetadata,
    ],
    *,
    overwrite: bool = False,
) -> Iterator[tuple[str, Group | Array]]

Create a hierarchy of arrays or groups rooted at this group.

This function will parse its input to ensure that the hierarchy is complete. Any implicit groups will be inserted as needed. For example, an input like {'a/b': GroupMetadata} will be parsed to {'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}.

Explicitly specifying a root group, e.g. with nodes = {'': GroupMetadata()} is an error because this group instance is the root group.

After input parsing, this function then creates all the nodes in the hierarchy concurrently.

Arrays and Groups are yielded in the order they are created. This order is not stable and should not be relied on.

Parameters:

  • nodes (dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]) –

    A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, relative to the path of the group. The values are instances of GroupMetadata or ArrayMetadata. Note that all values must have the same zarr_format as the parent group -- it is an error to mix zarr versions in the same hierarchy.

    Leading "/" characters from keys will be removed.

  • overwrite (bool, default: False ) –

    Whether to overwrite existing nodes. Defaults to False, in which case an error is raised instead of overwriting an existing array or group.

    This function will not erase an existing group unless that group is explicitly named in nodes. If nodes defines implicit groups, e.g. {`'a/b/c': GroupMetadata}, and a group already exists at path a, then this function will leave the group at a as-is.

Yields:

  • tuple[str, Array | Group].

Examples:

>>> import zarr
>>> from zarr.core.group import GroupMetadata
>>> root = zarr.create_group(store={})
>>> for key, val in root.create_hierarchy({'a/b/c': GroupMetadata()}):
...   print(key, val)
...
<AsyncGroup memory://123209880766144/a>
<AsyncGroup memory://123209880766144/a/b/c>
<AsyncGroup memory://123209880766144/a/b>
Source code in zarr/core/group.py
def create_hierarchy(
    self,
    nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata],
    *,
    overwrite: bool = False,
) -> Iterator[tuple[str, Group | Array]]:
    """
    Create a hierarchy of arrays or groups rooted at this group.

    This function will parse its input to ensure that the hierarchy is complete. Any implicit groups
    will be inserted as needed. For example, an input like
    ```{'a/b': GroupMetadata}``` will be parsed to
    ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```.

    Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error
    because this group instance is the root group.

    After input parsing, this function then creates all the nodes in the hierarchy concurrently.

    Arrays and Groups are yielded in the order they are created. This order is not stable and
    should not be relied on.

    Parameters
    ----------
    nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]
        A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy,
        relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that
        all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the
        same hierarchy.

        Leading "/" characters from keys will be removed.
    overwrite : bool
        Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is
        raised instead of overwriting an existing array or group.

        This function will not erase an existing group unless that group is explicitly named in
        ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a
        group already exists at path ``a``, then this function will leave the group at ``a`` as-is.

    Yields
    ------
        tuple[str, Array | Group].

    Examples
    --------
    >>> import zarr
    >>> from zarr.core.group import GroupMetadata
    >>> root = zarr.create_group(store={})
    >>> for key, val in root.create_hierarchy({'a/b/c': GroupMetadata()}):
    ...   print(key, val)
    ...
    <AsyncGroup memory://123209880766144/a>
    <AsyncGroup memory://123209880766144/a/b/c>
    <AsyncGroup memory://123209880766144/a/b>
    """
    for key, node in self._sync_iter(
        self._async_group.create_hierarchy(nodes, overwrite=overwrite)
    ):
        yield (key, _parse_async_node(node))

empty

empty(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> Array

Create an empty array with the specified shape in this Group. The contents will be filled with the array's fill value or zeros if no fill value is provided.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Notes

The contents of an empty Zarr array are not defined. On attempting to retrieve data from an empty Zarr array, any values may be returned, and these are not guaranteed to be stable from one access to the next.

Source code in zarr/core/group.py
def empty(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
    """Create an empty array with the specified shape in this Group. The contents will be filled with
    the array's fill value or zeros if no fill value is provided.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Notes
    -----
    The contents of an empty Zarr array are not defined. On attempting to
    retrieve data from an empty Zarr array, any values may be returned,
    and these are not guaranteed to be stable from one access to the next.
    """
    return Array(self._sync(self._async_group.empty(name=name, shape=shape, **kwargs)))

empty_like

empty_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> Array

Create an empty sub-array like data. The contents will be filled with the array's fill value or zeros if no fill value is provided.

Parameters:

Returns:

  • Array

    The new array.

Notes

The contents of an empty Zarr array are not defined. On attempting to retrieve data from an empty Zarr array, any values may be returned, and these are not guaranteed to be stable from one access to the next.

Source code in zarr/core/group.py
def empty_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
    """Create an empty sub-array like `data`. The contents will be filled
    with the array's fill value or zeros if no fill value is provided.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create an empty array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.

    Notes
    -----
    The contents of an empty Zarr array are not defined. On attempting to
    retrieve data from an empty Zarr array, any values may be returned,
    and these are not guaranteed to be stable from one access to the next.
    """
    return Array(self._sync(self._async_group.empty_like(name=name, data=data, **kwargs)))

from_store classmethod

from_store(
    store: StoreLike,
    *,
    attributes: dict[str, Any] | None = None,
    zarr_format: ZarrFormat = 3,
    overwrite: bool = False,
) -> Group

Instantiate a group from an initialized store.

Parameters:

  • store (StoreLike) –

    StoreLike containing the Group.

  • attributes (dict, default: None ) –

    A dictionary of JSON-serializable values with user-defined attributes.

  • zarr_format ((2, 3), default: 2 ) –

    Zarr storage format version.

  • overwrite (bool, default: False ) –

    If True, do not raise an error if the group already exists.

Returns:

  • Group

    Group instantiated from the store.

Raises:

Source code in zarr/core/group.py
@classmethod
def from_store(
    cls,
    store: StoreLike,
    *,
    attributes: dict[str, Any] | None = None,
    zarr_format: ZarrFormat = 3,
    overwrite: bool = False,
) -> Group:
    """Instantiate a group from an initialized store.

    Parameters
    ----------
    store : StoreLike
        StoreLike containing the Group.
    attributes : dict, optional
        A dictionary of JSON-serializable values with user-defined attributes.
    zarr_format : {2, 3}, optional
        Zarr storage format version.
    overwrite : bool, optional
        If True, do not raise an error if the group already exists.

    Returns
    -------
    Group
        Group instantiated from the store.

    Raises
    ------
    ContainsArrayError, ContainsGroupError, ContainsArrayAndGroupError
    """
    attributes = attributes or {}
    obj = sync(
        AsyncGroup.from_store(
            store,
            attributes=attributes,
            overwrite=overwrite,
            zarr_format=zarr_format,
        ),
    )

    return cls(obj)

full

full(
    *,
    name: str,
    shape: tuple[int, ...],
    fill_value: Any | None,
    **kwargs: Any,
) -> Array

Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • fill_value (scalar) –

    Value to fill the array with.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def full(
    self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any
) -> Array:
    """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    fill_value : scalar
        Value to fill the array with.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """
    return Array(
        self._sync(
            self._async_group.full(name=name, shape=shape, fill_value=fill_value, **kwargs)
        )
    )

full_like

full_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> Array

Create a sub-array like data filled with the fill_value of data .

Parameters:

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def full_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
    """Create a sub-array like `data` filled with the `fill_value` of `data` .

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """
    return Array(self._sync(self._async_group.full_like(name=name, data=data, **kwargs)))

get

get(
    path: str, default: DefaultT | None = None
) -> Array | Group | DefaultT | None

Obtain a group member, returning default if not found.

Parameters:

  • path (str) –

    Group member name.

  • default (object, default: None ) –

    Default value to return if key is not found (default: None).

Returns:

  • object

    Group member (Array or Group) or default if not found.

Examples:

>>> import zarr
>>> group = Group.from_store(zarr.storage.MemoryStore()
>>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
>>> group.create_group(name="subgroup")
>>> group.get("subarray")
<Array memory://132270269438272/subarray shape=(10,) dtype=float64>
>>> group.get("subgroup")
<Group memory://132270269438272/subgroup>
>>> group.get("nonexistent", None)
Source code in zarr/core/group.py
def get(self, path: str, default: DefaultT | None = None) -> Array | Group | DefaultT | None:
    """Obtain a group member, returning default if not found.

    Parameters
    ----------
    path : str
        Group member name.
    default : object
        Default value to return if key is not found (default: None).

    Returns
    -------
    object
        Group member (Array or Group) or default if not found.

    Examples
    --------
    >>> import zarr
    >>> group = Group.from_store(zarr.storage.MemoryStore()
    >>> group.create_array(name="subarray", shape=(10,), chunks=(10,))
    >>> group.create_group(name="subgroup")
    >>> group.get("subarray")
    <Array memory://132270269438272/subarray shape=(10,) dtype=float64>
    >>> group.get("subgroup")
    <Group memory://132270269438272/subgroup>
    >>> group.get("nonexistent", None)

    """
    try:
        return self[path]
    except KeyError:
        return default

group_keys

group_keys() -> Generator[str, None]

Return an iterator over group member names.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_group("subgroup")
>>> for name in group.group_keys():
...     print(name)
subgroup
Source code in zarr/core/group.py
def group_keys(self) -> Generator[str, None]:
    """Return an iterator over group member names.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_group("subgroup")
    >>> for name in group.group_keys():
    ...     print(name)
    subgroup
    """
    for name, _ in self.groups():
        yield name

group_values

group_values() -> Generator[Group, None]

Return an iterator over group members.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_group("subgroup")
>>> for subgroup in group.group_values():
...     print(subgroup)
<Group memory://132270269438272/subgroup>
Source code in zarr/core/group.py
def group_values(self) -> Generator[Group, None]:
    """Return an iterator over group members.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_group("subgroup")
    >>> for subgroup in group.group_values():
    ...     print(subgroup)
    <Group memory://132270269438272/subgroup>
    """
    for _, group in self.groups():
        yield group

groups

groups() -> Generator[tuple[str, Group], None]

Return the sub-groups of this group as a generator of (name, group) pairs.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.create_group("subgroup")
>>> for name, subgroup in group.groups():
...     print(name, subgroup)
subgroup <Group memory://132270269438272/subgroup>
Source code in zarr/core/group.py
def groups(self) -> Generator[tuple[str, Group], None]:
    """Return the sub-groups of this group as a generator of (name, group) pairs.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.create_group("subgroup")
    >>> for name, subgroup in group.groups():
    ...     print(name, subgroup)
    subgroup <Group memory://132270269438272/subgroup>
    """
    for name, async_group in self._sync_iter(self._async_group.groups()):
        yield name, Group(async_group)

info_complete

info_complete() -> Any

Return information for a group.

If this group doesn't contain consolidated metadata then this will need to read from the backing Store.

Returns:

  • GroupInfo
Source code in zarr/core/group.py
def info_complete(self) -> Any:
    """
    Return information for a group.

    If this group doesn't contain consolidated metadata then
    this will need to read from the backing Store.

    Returns
    -------
    GroupInfo

    Related
    -------
    [zarr.Group.info][]
    """
    return self._sync(self._async_group.info_complete())

keys

keys() -> Generator[str, None]

Return an iterator over group member names.

Examples:

>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
>>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
>>> for name in g1.keys():
...     print(name)
baz
bar
foo
quux
Source code in zarr/core/group.py
def keys(self) -> Generator[str, None]:
    """Return an iterator over group member names.

    Examples
    --------
    >>> import zarr
    >>> g1 = zarr.group()
    >>> g2 = g1.create_group('foo')
    >>> g3 = g1.create_group('bar')
    >>> d1 = g1.create_array('baz', shape=(10,), chunks=(10,))
    >>> d2 = g1.create_array('quux', shape=(10,), chunks=(10,))
    >>> for name in g1.keys():
    ...     print(name)
    baz
    bar
    foo
    quux
    """
    yield from self._sync_iter(self._async_group.keys())

members

members(
    max_depth: int | None = 0,
    *,
    use_consolidated_for_children: bool = True,
) -> tuple[tuple[str, Array | Group], ...]

Returns an AsyncGenerator over the arrays and groups contained in this group. This method requires that store_path.store supports directory listing.

The results are not guaranteed to be ordered.

Parameters:

  • max_depth (int, default: 0 ) –

    The maximum number of levels of the hierarchy to include. By default, (max_depth=0) only immediate children are included. Set max_depth=None to include all nodes, and some positive integer to consider children within that many levels of the root Group.

  • use_consolidated_for_children (bool, default: True ) –

    Whether to use the consolidated metadata of child groups loaded from the store. Note that this only affects groups loaded from the store. If the current Group already has consolidated metadata, it will always be used.

Returns:

  • path ( tuple[str, Array | Group] ) –

    A string giving the path to the target, relative to the Group self.

  • value ( AsyncArray or AsyncGroup ) –

    The AsyncArray or AsyncGroup that is a child of self.

Source code in zarr/core/group.py
def members(
    self, max_depth: int | None = 0, *, use_consolidated_for_children: bool = True
) -> tuple[tuple[str, Array | Group], ...]:
    """
    Returns an AsyncGenerator over the arrays and groups contained in this group.
    This method requires that `store_path.store` supports directory listing.

    The results are not guaranteed to be ordered.

    Parameters
    ----------
    max_depth : int, default 0
        The maximum number of levels of the hierarchy to include. By
        default, (``max_depth=0``) only immediate children are included. Set
        ``max_depth=None`` to include all nodes, and some positive integer
        to consider children within that many levels of the root Group.
    use_consolidated_for_children : bool, default True
        Whether to use the consolidated metadata of child groups loaded
        from the store. Note that this only affects groups loaded from the
        store. If the current Group already has consolidated metadata, it
        will always be used.

    Returns
    -------
    path:
        A string giving the path to the target, relative to the Group ``self``.
    value: AsyncArray or AsyncGroup
        The AsyncArray or AsyncGroup that is a child of ``self``.
    """
    _members = self._sync_iter(self._async_group.members(max_depth=max_depth))

    return tuple((kv[0], _parse_async_node(kv[1])) for kv in _members)

move

move(source: str, dest: str) -> None

Move a sub-group or sub-array from one path to another.

Notes

Not implemented

Source code in zarr/core/group.py
def move(self, source: str, dest: str) -> None:
    """Move a sub-group or sub-array from one path to another.

    Notes
    -----
    Not implemented
    """
    return self._sync(self._async_group.move(source, dest))

nmembers

nmembers(max_depth: int | None = 0) -> int

Count the number of members in this group.

Parameters:

  • max_depth (int, default: 0 ) –

    The maximum number of levels of the hierarchy to include. By default, (max_depth=0) only immediate children are included. Set max_depth=None to include all nodes, and some positive integer to consider children within that many levels of the root Group.

Returns:

  • count ( int ) –
Source code in zarr/core/group.py
def nmembers(self, max_depth: int | None = 0) -> int:
    """Count the number of members in this group.

    Parameters
    ----------
    max_depth : int, default 0
        The maximum number of levels of the hierarchy to include. By
        default, (``max_depth=0``) only immediate children are included. Set
        ``max_depth=None`` to include all nodes, and some positive integer
        to consider children within that many levels of the root Group.

    Returns
    -------
    count : int
    """

    return self._sync(self._async_group.nmembers(max_depth=max_depth))

ones

ones(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> Array

Create an array, with one being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def ones(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
    """Create an array, with one being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """
    return Array(self._sync(self._async_group.ones(name=name, shape=shape, **kwargs)))

ones_like

ones_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> Array

Create a sub-array of ones like data.

Parameters:

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def ones_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
    """Create a sub-array of ones like `data`.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """
    return Array(self._sync(self._async_group.ones_like(name=name, data=data, **kwargs)))

open classmethod

open(
    store: StoreLike, zarr_format: ZarrFormat | None = 3
) -> Group

Open a group from an initialized store.

Parameters:

  • store (StoreLike) –

    Store containing the Group.

  • zarr_format ((2, 3, None), default: 2 ) –

    Zarr storage format version.

Returns:

  • Group

    Group instantiated from the store.

Source code in zarr/core/group.py
@classmethod
def open(
    cls,
    store: StoreLike,
    zarr_format: ZarrFormat | None = 3,
) -> Group:
    """Open a group from an initialized store.

    Parameters
    ----------
    store : StoreLike
        Store containing the Group.
    zarr_format : {2, 3, None}, optional
        Zarr storage format version.

    Returns
    -------
    Group
        Group instantiated from the store.
    """
    obj = sync(AsyncGroup.open(store, zarr_format=zarr_format))
    return cls(obj)

require_array

require_array(
    name: str, *, shape: ShapeLike, **kwargs: Any
) -> Array

Obtain an array, creating if it doesn't exist.

Other kwargs are as per zarr.Group.create_array.

Parameters:

Returns:

Source code in zarr/core/group.py
def require_array(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> Array:
    """Obtain an array, creating if it doesn't exist.

    Other `kwargs` are as per [zarr.Group.create_array][].

    Parameters
    ----------
    name : str
        Array name.
    **kwargs :
        See [zarr.Group.create_array][].

    Returns
    -------
    a : Array
    """
    return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs)))

require_dataset

require_dataset(
    name: str, *, shape: ShapeLike, **kwargs: Any
) -> Array

Obtain an array, creating if it doesn't exist.

Deprecated

Group.require_dataset() is deprecated since v3.0.0 and will be removed in v3.1.0. Use Group.require_array instead.

Arrays are known as "datasets" in HDF5 terminology. For compatibility with h5py, Zarr groups also implement the zarr.Group.create_dataset method.

Other kwargs are as per zarr.Group.create_dataset.

Parameters:

Returns:

Source code in zarr/core/group.py
@deprecated("Use Group.require_array instead.", category=ZarrDeprecationWarning)
def require_dataset(self, name: str, *, shape: ShapeLike, **kwargs: Any) -> Array:
    """Obtain an array, creating if it doesn't exist.

    !!! warning "Deprecated"
        `Group.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
        Use `Group.require_array` instead.

    Arrays are known as "datasets" in HDF5 terminology. For compatibility
    with h5py, Zarr groups also implement the [zarr.Group.create_dataset][] method.

    Other `kwargs` are as per [zarr.Group.create_dataset][].

    Parameters
    ----------
    name : str
        Array name.
    **kwargs :
        See [zarr.Group.create_dataset][].

    Returns
    -------
    a : Array
    """
    return Array(self._sync(self._async_group.require_array(name, shape=shape, **kwargs)))

require_group

require_group(name: str, **kwargs: Any) -> Group

Obtain a sub-group, creating one if it doesn't exist.

Parameters:

  • name (str) –

    Group name.

Returns:

Source code in zarr/core/group.py
def require_group(self, name: str, **kwargs: Any) -> Group:
    """Obtain a sub-group, creating one if it doesn't exist.

    Parameters
    ----------
    name : str
        Group name.

    Returns
    -------
    g : Group
    """
    return Group(self._sync(self._async_group.require_group(name, **kwargs)))

require_groups

require_groups(*names: str) -> tuple[Group, ...]

Convenience method to require multiple groups in a single call.

Parameters:

  • *names (str, default: () ) –

    Group names.

Returns:

  • groups ( tuple of Groups ) –
Source code in zarr/core/group.py
def require_groups(self, *names: str) -> tuple[Group, ...]:
    """Convenience method to require multiple groups in a single call.

    Parameters
    ----------
    *names : str
        Group names.

    Returns
    -------
    groups : tuple of Groups
    """
    return tuple(map(Group, self._sync(self._async_group.require_groups(*names))))

tree

tree(
    expand: bool | None = None, level: int | None = None
) -> Any

Return a tree-like representation of a hierarchy.

This requires the optional rich dependency.

Parameters:

  • expand (bool, default: None ) –

    This keyword is not yet supported. A NotImplementedError is raised if it's used.

  • level (int, default: None ) –

    The maximum depth below this Group to display in the tree.

Returns:

  • TreeRepr

    A pretty-printable object displaying the hierarchy.

Source code in zarr/core/group.py
def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
    """
    Return a tree-like representation of a hierarchy.

    This requires the optional ``rich`` dependency.

    Parameters
    ----------
    expand : bool, optional
        This keyword is not yet supported. A NotImplementedError is raised if
        it's used.
    level : int, optional
        The maximum depth below this Group to display in the tree.

    Returns
    -------
    TreeRepr
        A pretty-printable object displaying the hierarchy.
    """
    return self._sync(self._async_group.tree(expand=expand, level=level))

update_attributes

update_attributes(new_attributes: dict[str, Any]) -> Group

Update the attributes of this group.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> group.update_attributes({"foo": "bar"})
>>> group.attrs.asdict()
{'foo': 'bar'}
Source code in zarr/core/group.py
def update_attributes(self, new_attributes: dict[str, Any]) -> Group:
    """Update the attributes of this group.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> group.update_attributes({"foo": "bar"})
    >>> group.attrs.asdict()
    {'foo': 'bar'}
    """
    self._sync(self._async_group.update_attributes(new_attributes))
    return self

update_attributes_async async

update_attributes_async(
    new_attributes: dict[str, Any],
) -> Group

Update the attributes of this group.

Examples:

>>> import zarr
>>> group = zarr.group()
>>> await group.update_attributes_async({"foo": "bar"})
>>> group.attrs.asdict()
{'foo': 'bar'}
Source code in zarr/core/group.py
async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group:
    """Update the attributes of this group.

    Examples
    --------
    >>> import zarr
    >>> group = zarr.group()
    >>> await group.update_attributes_async({"foo": "bar"})
    >>> group.attrs.asdict()
    {'foo': 'bar'}
    """
    new_metadata = replace(self.metadata, attributes=new_attributes)

    # Write new metadata
    to_save = new_metadata.to_buffer_dict(default_buffer_prototype())
    awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()]
    await asyncio.gather(*awaitables)

    async_group = replace(self._async_group, metadata=new_metadata)
    return replace(self, _async_group=async_group)

zeros

zeros(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> Array

Create an array, with zero being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def zeros(self, *, name: str, shape: tuple[int, ...], **kwargs: Any) -> Array:
    """Create an array, with zero being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """
    return Array(self._sync(self._async_group.zeros(name=name, shape=shape, **kwargs)))

zeros_like

zeros_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> Array

Create a sub-array of zeros like data.

Parameters:

Returns:

  • Array

    The new array.

Source code in zarr/core/group.py
def zeros_like(self, *, name: str, data: async_api.ArrayLike, **kwargs: Any) -> Array:
    """Create a sub-array of zeros like `data`.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    Array
        The new array.
    """

    return Array(self._sync(self._async_group.zeros_like(name=name, data=data, **kwargs)))

zarr.AsyncGroup dataclass

Asynchronous Group object.

Source code in zarr/core/group.py
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
@dataclass(frozen=True)
class AsyncGroup:
    """
    Asynchronous Group object.
    """

    metadata: GroupMetadata
    store_path: StorePath

    # TODO: make this correct and work
    # TODO: ensure that this can be bound properly to subclass of AsyncGroup

    @classmethod
    async def from_store(
        cls,
        store: StoreLike,
        *,
        attributes: dict[str, Any] | None = None,
        overwrite: bool = False,
        zarr_format: ZarrFormat = 3,
    ) -> AsyncGroup:
        store_path = await make_store_path(store)

        if overwrite:
            if store_path.store.supports_deletes:
                await store_path.delete_dir()
            else:
                await ensure_no_existing_node(store_path, zarr_format=zarr_format)
        else:
            await ensure_no_existing_node(store_path, zarr_format=zarr_format)
        attributes = attributes or {}
        group = cls(
            metadata=GroupMetadata(attributes=attributes, zarr_format=zarr_format),
            store_path=store_path,
        )
        await group._save_metadata(ensure_parents=True)
        return group

    @classmethod
    async def open(
        cls,
        store: StoreLike,
        zarr_format: ZarrFormat | None = 3,
        use_consolidated: bool | str | None = None,
    ) -> AsyncGroup:
        """Open a new AsyncGroup

        Parameters
        ----------
        store : StoreLike
        zarr_format : {2, 3}, optional
        use_consolidated : bool or str, default None
            Whether to use consolidated metadata.

            By default, consolidated metadata is used if it's present in the
            store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file
            for Zarr format 2) and the Store supports it.

            To explicitly require consolidated metadata, set ``use_consolidated=True``.
            In this case, if the Store doesn't support consolidation or consolidated metadata is
            not found, a ``ValueError`` exception is raised.

            To explicitly *not* use consolidated metadata, set ``use_consolidated=False``,
            which will fall back to using the regular, non consolidated metadata.

            Zarr format 2 allowed configuring the key storing the consolidated metadata
            (``.zmetadata`` by default). Specify the custom key as ``use_consolidated``
            to load consolidated metadata from a non-default key.
        """
        store_path = await make_store_path(store)
        if not store_path.store.supports_consolidated_metadata:
            # Fail if consolidated metadata was requested but the Store doesn't support it
            if use_consolidated:
                store_name = type(store_path.store).__name__
                raise ValueError(
                    f"The Zarr store in use ({store_name}) doesn't support consolidated metadata."
                )

            # if use_consolidated was None (optional), the Store dictates it doesn't want consolidation
            use_consolidated = False

        consolidated_key = ZMETADATA_V2_JSON

        if (zarr_format == 2 or zarr_format is None) and isinstance(use_consolidated, str):
            consolidated_key = use_consolidated

        if zarr_format == 2:
            paths = [store_path / ZGROUP_JSON, store_path / ZATTRS_JSON]
            if use_consolidated or use_consolidated is None:
                paths.append(store_path / consolidated_key)

            zgroup_bytes, zattrs_bytes, *rest = await asyncio.gather(
                *[path.get() for path in paths]
            )
            if zgroup_bytes is None:
                raise FileNotFoundError(store_path)

            if use_consolidated or use_consolidated is None:
                maybe_consolidated_metadata_bytes = rest[0]

            else:
                maybe_consolidated_metadata_bytes = None

        elif zarr_format == 3:
            zarr_json_bytes = await (store_path / ZARR_JSON).get()
            if zarr_json_bytes is None:
                raise FileNotFoundError(store_path)
        elif zarr_format is None:
            (
                zarr_json_bytes,
                zgroup_bytes,
                zattrs_bytes,
                maybe_consolidated_metadata_bytes,
            ) = await asyncio.gather(
                (store_path / ZARR_JSON).get(),
                (store_path / ZGROUP_JSON).get(),
                (store_path / ZATTRS_JSON).get(),
                (store_path / str(consolidated_key)).get(),
            )
            if zarr_json_bytes is not None and zgroup_bytes is not None:
                # warn and favor v3
                msg = f"Both zarr.json (Zarr format 3) and .zgroup (Zarr format 2) metadata objects exist at {store_path}. Zarr format 3 will be used."
                warnings.warn(msg, category=ZarrUserWarning, stacklevel=1)
            if zarr_json_bytes is None and zgroup_bytes is None:
                raise FileNotFoundError(
                    f"could not find zarr.json or .zgroup objects in {store_path}"
                )
            # set zarr_format based on which keys were found
            if zarr_json_bytes is not None:
                zarr_format = 3
            else:
                zarr_format = 2
        else:
            msg = f"Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '{zarr_format}'."  # type: ignore[unreachable]
            raise MetadataValidationError(msg)

        if zarr_format == 2:
            # this is checked above, asserting here for mypy
            assert zgroup_bytes is not None

            if use_consolidated and maybe_consolidated_metadata_bytes is None:
                # the user requested consolidated metadata, but it was missing
                raise ValueError(consolidated_key)

            elif use_consolidated is False:
                # the user explicitly opted out of consolidated_metadata.
                # Discard anything we might have read.
                maybe_consolidated_metadata_bytes = None

            return cls._from_bytes_v2(
                store_path, zgroup_bytes, zattrs_bytes, maybe_consolidated_metadata_bytes
            )
        else:
            # V3 groups are comprised of a zarr.json object
            assert zarr_json_bytes is not None
            if not isinstance(use_consolidated, bool | None):
                raise TypeError("use_consolidated must be a bool or None for Zarr format 3.")

            return cls._from_bytes_v3(
                store_path,
                zarr_json_bytes,
                use_consolidated=use_consolidated,
            )

    @classmethod
    def _from_bytes_v2(
        cls,
        store_path: StorePath,
        zgroup_bytes: Buffer,
        zattrs_bytes: Buffer | None,
        consolidated_metadata_bytes: Buffer | None,
    ) -> AsyncGroup:
        # V2 groups are comprised of a .zgroup and .zattrs objects
        zgroup = json.loads(zgroup_bytes.to_bytes())
        zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {}
        group_metadata = {**zgroup, "attributes": zattrs}

        if consolidated_metadata_bytes is not None:
            v2_consolidated_metadata = json.loads(consolidated_metadata_bytes.to_bytes())
            v2_consolidated_metadata = v2_consolidated_metadata["metadata"]
            # We already read zattrs and zgroup. Should we ignore these?
            v2_consolidated_metadata.pop(".zattrs", None)
            v2_consolidated_metadata.pop(".zgroup", None)

            consolidated_metadata: defaultdict[str, dict[str, Any]] = defaultdict(dict)

            # keys like air/.zarray, air/.zattrs
            for k, v in v2_consolidated_metadata.items():
                path, kind = k.rsplit("/.", 1)

                if kind == "zarray":
                    consolidated_metadata[path].update(v)
                elif kind == "zattrs":
                    consolidated_metadata[path]["attributes"] = v
                elif kind == "zgroup":
                    consolidated_metadata[path].update(v)
                else:
                    raise ValueError(f"Invalid file type '{kind}' at path '{path}")

            group_metadata["consolidated_metadata"] = {
                "metadata": dict(consolidated_metadata),
                "kind": "inline",
                "must_understand": False,
            }

        return cls.from_dict(store_path, group_metadata)

    @classmethod
    def _from_bytes_v3(
        cls,
        store_path: StorePath,
        zarr_json_bytes: Buffer,
        use_consolidated: bool | None,
    ) -> AsyncGroup:
        group_metadata = json.loads(zarr_json_bytes.to_bytes())
        if use_consolidated and group_metadata.get("consolidated_metadata") is None:
            msg = f"Consolidated metadata requested with 'use_consolidated=True' but not found in '{store_path.path}'."
            raise ValueError(msg)

        elif use_consolidated is False:
            # Drop consolidated metadata if it's there.
            group_metadata.pop("consolidated_metadata", None)

        return cls.from_dict(store_path, group_metadata)

    @classmethod
    def from_dict(
        cls,
        store_path: StorePath,
        data: dict[str, Any],
    ) -> AsyncGroup:
        node_type = data.pop("node_type", None)
        if node_type == "array":
            msg = f"An array already exists in store {store_path.store} at path {store_path.path}."
            raise ContainsArrayError(msg)
        elif node_type not in ("group", None):
            msg = f"Node type in metadata ({node_type}) is not 'group'"
            raise GroupNotFoundError(msg)
        return cls(
            metadata=GroupMetadata.from_dict(data),
            store_path=store_path,
        )

    async def setitem(self, key: str, value: Any) -> None:
        """
        Fastpath for creating a new array
        New arrays will be created with default array settings for the array type.

        Parameters
        ----------
        key : str
            Array name
        value : array-like
            Array data
        """
        path = self.store_path / key
        await async_api.save_array(
            store=path, arr=value, zarr_format=self.metadata.zarr_format, overwrite=True
        )

    async def getitem(
        self,
        key: str,
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup:
        """
        Get a subarray or subgroup from the group.

        Parameters
        ----------
        key : str
            Array or group name

        Returns
        -------
        AsyncArray or AsyncGroup
        """
        store_path = self.store_path / key
        logger.debug("key=%s, store_path=%s", key, store_path)

        # Consolidated metadata lets us avoid some I/O operations so try that first.
        if self.metadata.consolidated_metadata is not None:
            return self._getitem_consolidated(store_path, key, prefix=self.name)
        try:
            return await get_node(
                store=store_path.store, path=store_path.path, zarr_format=self.metadata.zarr_format
            )
        except FileNotFoundError as e:
            raise KeyError(key) from e

    def _getitem_consolidated(
        self, store_path: StorePath, key: str, prefix: str
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup:
        # getitem, in the special case where we have consolidated metadata.
        # Note that this is a regular def (non async) function.
        # This shouldn't do any additional I/O.

        # the caller needs to verify this!
        assert self.metadata.consolidated_metadata is not None

        # we support nested getitems like group/subgroup/array
        indexers = normalize_path(key).split("/")
        indexers.reverse()
        metadata: ArrayV2Metadata | ArrayV3Metadata | GroupMetadata = self.metadata

        while indexers:
            indexer = indexers.pop()
            if isinstance(metadata, ArrayV2Metadata | ArrayV3Metadata):
                # we've indexed into an array with group["array/subarray"]. Invalid.
                raise KeyError(key)
            if metadata.consolidated_metadata is None:
                # we've indexed into a group without consolidated metadata.
                # This isn't normal; typically, consolidated metadata
                # will include explicit markers for when there are no child
                # nodes as metadata={}.
                # We have some freedom in exactly how we interpret this case.
                # For now, we treat None as the same as {}, i.e. we don't
                # have any children.
                raise KeyError(key)
            try:
                metadata = metadata.consolidated_metadata.metadata[indexer]
            except KeyError as e:
                # The Group Metadata has consolidated metadata, but the key
                # isn't present. We trust this to mean that the key isn't in
                # the hierarchy, and *don't* fall back to checking the store.
                msg = f"'{key}' not found in consolidated metadata."
                raise KeyError(msg) from e

        # update store_path to ensure that AsyncArray/Group.name is correct
        if prefix != "/":
            key = "/".join([prefix.lstrip("/"), key])
        store_path = StorePath(store=store_path.store, path=key)

        if isinstance(metadata, GroupMetadata):
            return AsyncGroup(metadata=metadata, store_path=store_path)
        else:
            return AsyncArray(metadata=metadata, store_path=store_path)

    async def delitem(self, key: str) -> None:
        """Delete a group member.

        Parameters
        ----------
        key : str
            Array or group name
        """
        store_path = self.store_path / key

        await store_path.delete_dir()
        if self.metadata.consolidated_metadata:
            self.metadata.consolidated_metadata.metadata.pop(key, None)
            await self._save_metadata()

    async def get(
        self, key: str, default: DefaultT | None = None
    ) -> AsyncArray[Any] | AsyncGroup | DefaultT | None:
        """Obtain a group member, returning default if not found.

        Parameters
        ----------
        key : str
            Group member name.
        default : object
            Default value to return if key is not found (default: None).

        Returns
        -------
        object
            Group member (AsyncArray or AsyncGroup) or default if not found.
        """
        try:
            return await self.getitem(key)
        except KeyError:
            return default

    async def _save_metadata(self, ensure_parents: bool = False) -> None:
        await save_metadata(self.store_path, self.metadata, ensure_parents=ensure_parents)

    @property
    def path(self) -> str:
        """Storage path."""
        return self.store_path.path

    @property
    def name(self) -> str:
        """Group name following h5py convention."""
        if self.path:
            # follow h5py convention: add leading slash
            name = self.path
            if name[0] != "/":
                name = "/" + name
            return name
        return "/"

    @property
    def basename(self) -> str:
        """Final component of name."""
        return self.name.split("/")[-1]

    @property
    def attrs(self) -> dict[str, Any]:
        return self.metadata.attributes

    @property
    def info(self) -> Any:
        """
        Return a visual representation of the statically known information about a group.

        Note that this doesn't include dynamic information, like the number of child
        Groups or Arrays.

        Returns
        -------
        GroupInfo

        Related
        -------
        [zarr.AsyncGroup.info_complete][]
            All information about a group, including dynamic information
        """

        if self.metadata.consolidated_metadata:
            members = list(self.metadata.consolidated_metadata.flattened_metadata.values())
        else:
            members = None
        return self._info(members=members)

    async def info_complete(self) -> Any:
        """
        Return all the information for a group.

        This includes dynamic information like the number
        of child Groups or Arrays. If this group doesn't contain consolidated
        metadata then this will need to read from the backing Store.

        Returns
        -------
        GroupInfo

        Related
        -------
        [zarr.AsyncGroup.info][]
        """
        members = [x[1].metadata async for x in self.members(max_depth=None)]
        return self._info(members=members)

    def _info(
        self, members: list[ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] | None = None
    ) -> Any:
        kwargs = {}
        if members is not None:
            kwargs["_count_members"] = len(members)
            count_arrays = 0
            count_groups = 0
            for member in members:
                if isinstance(member, GroupMetadata):
                    count_groups += 1
                else:
                    count_arrays += 1
            kwargs["_count_arrays"] = count_arrays
            kwargs["_count_groups"] = count_groups

        return GroupInfo(
            _name=self.store_path.path,
            _read_only=self.read_only,
            _store_type=type(self.store_path.store).__name__,
            _zarr_format=self.metadata.zarr_format,
            # maybe do a typeddict
            **kwargs,  # type: ignore[arg-type]
        )

    @property
    def store(self) -> Store:
        return self.store_path.store

    @property
    def read_only(self) -> bool:
        # Backwards compatibility for 2.x
        return self.store_path.read_only

    @property
    def synchronizer(self) -> None:
        # Backwards compatibility for 2.x
        # Not implemented in 3.x yet.
        return None

    async def create_group(
        self,
        name: str,
        *,
        overwrite: bool = False,
        attributes: dict[str, Any] | None = None,
    ) -> AsyncGroup:
        """Create a sub-group.

        Parameters
        ----------
        name : str
            Group name.
        overwrite : bool, optional
            If True, do not raise an error if the group already exists.
        attributes : dict, optional
            Group attributes.

        Returns
        -------
        g : AsyncGroup
        """
        attributes = attributes or {}
        return await type(self).from_store(
            self.store_path / name,
            attributes=attributes,
            overwrite=overwrite,
            zarr_format=self.metadata.zarr_format,
        )

    async def require_group(self, name: str, overwrite: bool = False) -> AsyncGroup:
        """Obtain a sub-group, creating one if it doesn't exist.

        Parameters
        ----------
        name : str
            Group name.
        overwrite : bool, optional
            Overwrite any existing group with given `name` if present.

        Returns
        -------
        g : AsyncGroup
        """
        if overwrite:
            # TODO: check that overwrite=True errors if an array exists where the group is being created
            grp = await self.create_group(name, overwrite=True)
        else:
            try:
                item: (
                    AsyncGroup | AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]
                ) = await self.getitem(name)
                if not isinstance(item, AsyncGroup):
                    raise TypeError(
                        f"Incompatible object ({item.__class__.__name__}) already exists"
                    )
                assert isinstance(item, AsyncGroup)  # make mypy happy
                grp = item
            except KeyError:
                grp = await self.create_group(name)
        return grp

    async def require_groups(self, *names: str) -> tuple[AsyncGroup, ...]:
        """Convenience method to require multiple groups in a single call.

        Parameters
        ----------
        *names : str
            Group names.

        Returns
        -------
        Tuple[AsyncGroup, ...]
        """
        if not names:
            return ()
        return tuple(await asyncio.gather(*(self.require_group(name) for name in names)))

    async def create_array(
        self,
        name: str,
        *,
        shape: ShapeLike | None = None,
        dtype: ZDTypeLike | None = None,
        data: np.ndarray[Any, np.dtype[Any]] | None = None,
        chunks: tuple[int, ...] | Literal["auto"] = "auto",
        shards: ShardsLike | None = None,
        filters: FiltersLike = "auto",
        compressors: CompressorsLike = "auto",
        compressor: CompressorLike = "auto",
        serializer: SerializerLike = "auto",
        fill_value: Any | None = DEFAULT_FILL_VALUE,
        order: MemoryOrder | None = None,
        attributes: dict[str, JSON] | None = None,
        chunk_key_encoding: ChunkKeyEncodingLike | None = None,
        dimension_names: DimensionNames = None,
        storage_options: dict[str, Any] | None = None,
        overwrite: bool = False,
        config: ArrayConfigLike | None = None,
        write_data: bool = True,
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an array within this group.

        This method lightly wraps [zarr.core.array.create_array][].

        Parameters
        ----------
        name : str
            The name of the array relative to the group. If ``path`` is ``None``, the array will be located
            at the root of the store.
        shape : tuple[int, ...]
            Shape of the array.
        dtype : npt.DTypeLike
            Data type of the array.
        chunks : tuple[int, ...], optional
            Chunk shape of the array.
            If not specified, default are guessed based on the shape and dtype.
        shards : tuple[int, ...], optional
            Shard shape of the array. The default value of ``None`` results in no sharding at all.
        filters : Iterable[Codec] | Literal["auto"], optional
            Iterable of filters to apply to each chunk of the array, in order, before serializing that
            chunk to bytes.

            For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
            and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
            dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

            For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
            the order if your filters is consistent with the behavior of each filter.

            The default value of ``"auto"`` instructs Zarr to use a default used based on the data
            type of the array and the Zarr format specified. For all data types in Zarr V3, and most
            data types in Zarr V2, the default filters are empty. The only cases where default filters
            are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
            [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
            the default filters contains a single element which is a codec specific to that particular data type.

            To create an array with no filters, provide an empty iterable or the value ``None``.
        compressors : Iterable[Codec], optional
            List of compressors to apply to the array. Compressors are applied in order, and after any
            filters are applied (if any are specified) and the data is serialized into bytes.

            For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
            returns another bytestream. Multiple compressors my be provided for Zarr format 3.
            If no ``compressors`` are provided, a default set of compressors will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_compressors``
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit default compressors.

            For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
            be provided for Zarr format 2.
            If no ``compressor`` is provided, a default compressor will be used.
            in [`zarr.config`][zarr.config].
            Use ``None`` to omit the default compressor.
        compressor : Codec, optional
            Deprecated in favor of ``compressors``.
        serializer : dict[str, JSON] | ArrayBytesCodec, optional
            Array-to-bytes codec to use for encoding the array data.
            Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
            If no ``serializer`` is provided, a default serializer will be used.
            These defaults can be changed by modifying the value of ``array.v3_default_serializer``
            in [`zarr.config`][zarr.config].
        fill_value : Any, optional
            Fill value for the array.
        order : {"C", "F"}, optional
            The memory of the array (default is "C").
            For Zarr format 2, this parameter sets the memory order of the array.
            For Zarr format 3, this parameter is deprecated, because memory order
            is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
            order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
            If no ``order`` is provided, a default order will be used.
            This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
        attributes : dict, optional
            Attributes for the array.
        chunk_key_encoding : ChunkKeyEncoding, optional
            A specification of how the chunk keys are represented in storage.
            For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
            For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
        dimension_names : Iterable[str], optional
            The names of the dimensions (default is None).
            Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
        storage_options : dict, optional
            If using an fsspec URL to create the store, these will be passed to the backend implementation.
            Ignored otherwise.
        overwrite : bool, default False
            Whether to overwrite an array with the same name in the store, if one exists.
        config : ArrayConfig or ArrayConfigLike, optional
            Runtime configuration for the array.
        write_data : bool
            If a pre-existing array-like object was provided to this function via the ``data`` parameter
            then ``write_data`` determines whether the values in that array-like object should be
            written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
            array will be left empty.

        Returns
        -------
        AsyncArray

        """
        compressors = _parse_deprecated_compressor(
            compressor, compressors, zarr_format=self.metadata.zarr_format
        )
        return await create_array(
            store=self.store_path,
            name=name,
            shape=shape,
            dtype=dtype,
            data=data,
            chunks=chunks,
            shards=shards,
            filters=filters,
            compressors=compressors,
            serializer=serializer,
            fill_value=fill_value,
            order=order,
            zarr_format=self.metadata.zarr_format,
            attributes=attributes,
            chunk_key_encoding=chunk_key_encoding,
            dimension_names=dimension_names,
            storage_options=storage_options,
            overwrite=overwrite,
            config=config,
            write_data=write_data,
        )

    @deprecated("Use AsyncGroup.create_array instead.", category=ZarrDeprecationWarning)
    async def create_dataset(
        self, name: str, *, shape: ShapeLike, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an array.

        !!! warning "Deprecated"
            `AsyncGroup.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
            Use `AsyncGroup.create_array` instead.

        Arrays are known as "datasets" in HDF5 terminology. For compatibility
        with h5py, Zarr groups also implement the [zarr.AsyncGroup.require_dataset][] method.

        Parameters
        ----------
        name : str
            Array name.
        **kwargs : dict
            Additional arguments passed to [zarr.AsyncGroup.create_array][].

        Returns
        -------
        a : AsyncArray
        """
        data = kwargs.pop("data", None)
        # create_dataset in zarr 2.x requires shape but not dtype if data is
        # provided. Allow this configuration by inferring dtype from data if
        # necessary and passing it to create_array
        if "dtype" not in kwargs and data is not None:
            kwargs["dtype"] = data.dtype
        array = await self.create_array(name, shape=shape, **kwargs)
        if data is not None:
            await array.setitem(slice(None), data)
        return array

    @deprecated("Use AsyncGroup.require_array instead.", category=ZarrDeprecationWarning)
    async def require_dataset(
        self,
        name: str,
        *,
        shape: tuple[int, ...],
        dtype: npt.DTypeLike = None,
        exact: bool = False,
        **kwargs: Any,
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Obtain an array, creating if it doesn't exist.

        !!! warning "Deprecated"
            `AsyncGroup.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
            Use `AsyncGroup.require_dataset` instead.

        Arrays are known as "datasets" in HDF5 terminology. For compatibility
        with h5py, Zarr groups also implement the [zarr.AsyncGroup.create_dataset][] method.

        Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][].

        Parameters
        ----------
        name : str
            Array name.
        shape : int or tuple of ints
            Array shape.
        dtype : str or dtype, optional
            NumPy dtype.
        exact : bool, optional
            If True, require `dtype` to match exactly. If false, require
            `dtype` can be cast from array dtype.

        Returns
        -------
        a : AsyncArray
        """
        return await self.require_array(name, shape=shape, dtype=dtype, exact=exact, **kwargs)

    async def require_array(
        self,
        name: str,
        *,
        shape: ShapeLike,
        dtype: npt.DTypeLike = None,
        exact: bool = False,
        **kwargs: Any,
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Obtain an array, creating if it doesn't exist.

        Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][].

        Parameters
        ----------
        name : str
            Array name.
        shape : int or tuple of ints
            Array shape.
        dtype : str or dtype, optional
            NumPy dtype.
        exact : bool, optional
            If True, require `dtype` to match exactly. If false, require
            `dtype` can be cast from array dtype.

        Returns
        -------
        a : AsyncArray
        """
        try:
            ds = await self.getitem(name)
            if not isinstance(ds, AsyncArray):
                raise TypeError(f"Incompatible object ({ds.__class__.__name__}) already exists")

            shape = parse_shapelike(shape)
            if shape != ds.shape:
                raise TypeError(f"Incompatible shape ({ds.shape} vs {shape})")

            dtype = np.dtype(dtype)
            if exact:
                if ds.dtype != dtype:
                    raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})")
            else:
                if not np.can_cast(ds.dtype, dtype):
                    raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})")
        except KeyError:
            ds = await self.create_array(name, shape=shape, dtype=dtype, **kwargs)

        return ds

    async def update_attributes(self, new_attributes: dict[str, Any]) -> AsyncGroup:
        """Update group attributes.

        Parameters
        ----------
        new_attributes : dict
            New attributes to set on the group.

        Returns
        -------
        self : AsyncGroup
        """
        self.metadata.attributes.update(new_attributes)

        # Write new metadata
        await self._save_metadata()

        return self

    def __repr__(self) -> str:
        return f"<AsyncGroup {self.store_path}>"

    async def nmembers(
        self,
        max_depth: int | None = 0,
    ) -> int:
        """Count the number of members in this group.

        Parameters
        ----------
        max_depth : int, default 0
            The maximum number of levels of the hierarchy to include. By
            default, (``max_depth=0``) only immediate children are included. Set
            ``max_depth=None`` to include all nodes, and some positive integer
            to consider children within that many levels of the root Group.

        Returns
        -------
        count : int
        """
        # check if we can use consolidated metadata, which requires that we have non-None
        # consolidated metadata at all points in the hierarchy.
        if self.metadata.consolidated_metadata is not None:
            if max_depth is not None and max_depth < 0:
                raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead")
            if max_depth is None:
                return len(self.metadata.consolidated_metadata.flattened_metadata)
            else:
                return len(
                    [
                        x
                        for x in self.metadata.consolidated_metadata.flattened_metadata
                        if x.count("/") <= max_depth
                    ]
                )
        # TODO: consider using aioitertools.builtins.sum for this
        # return await aioitertools.builtins.sum((1 async for _ in self.members()), start=0)
        n = 0
        async for _ in self.members(max_depth=max_depth):
            n += 1
        return n

    async def members(
        self,
        max_depth: int | None = 0,
        *,
        use_consolidated_for_children: bool = True,
    ) -> AsyncGenerator[
        tuple[str, AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup],
        None,
    ]:
        """
        Returns an AsyncGenerator over the arrays and groups contained in this group.
        This method requires that `store_path.store` supports directory listing.

        The results are not guaranteed to be ordered.

        Parameters
        ----------
        max_depth : int, default 0
            The maximum number of levels of the hierarchy to include. By
            default, (``max_depth=0``) only immediate children are included. Set
            ``max_depth=None`` to include all nodes, and some positive integer
            to consider children within that many levels of the root Group.
        use_consolidated_for_children : bool, default True
            Whether to use the consolidated metadata of child groups loaded
            from the store. Note that this only affects groups loaded from the
            store. If the current Group already has consolidated metadata, it
            will always be used.

        Returns
        -------
        path:
            A string giving the path to the target, relative to the Group ``self``.
        value: AsyncArray or AsyncGroup
            The AsyncArray or AsyncGroup that is a child of ``self``.
        """
        if max_depth is not None and max_depth < 0:
            raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead")
        async for item in self._members(
            max_depth=max_depth, use_consolidated_for_children=use_consolidated_for_children
        ):
            yield item

    def _members_consolidated(
        self, max_depth: int | None, prefix: str = ""
    ) -> Generator[
        tuple[str, AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup],
        None,
    ]:
        consolidated_metadata = self.metadata.consolidated_metadata

        do_recursion = max_depth is None or max_depth > 0

        # we kind of just want the top-level keys.
        if consolidated_metadata is not None:
            for key in consolidated_metadata.metadata:
                obj = self._getitem_consolidated(
                    self.store_path, key, prefix=self.name
                )  # Metadata -> Group/Array
                key = f"{prefix}/{key}".lstrip("/")
                yield key, obj

                if do_recursion and isinstance(obj, AsyncGroup):
                    if max_depth is None:
                        new_depth = None
                    else:
                        new_depth = max_depth - 1
                    yield from obj._members_consolidated(new_depth, prefix=key)

    async def _members(
        self, max_depth: int | None, *, use_consolidated_for_children: bool = True
    ) -> AsyncGenerator[
        tuple[str, AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata] | AsyncGroup], None
    ]:
        skip_keys: tuple[str, ...]
        if self.metadata.zarr_format == 2:
            skip_keys = (".zattrs", ".zgroup", ".zarray", ".zmetadata")
        elif self.metadata.zarr_format == 3:
            skip_keys = ("zarr.json",)
        else:
            raise ValueError(f"Unknown Zarr format: {self.metadata.zarr_format}")

        if self.metadata.consolidated_metadata is not None:
            members = self._members_consolidated(max_depth=max_depth)
            for member in members:
                yield member
            return

        if not self.store_path.store.supports_listing:
            msg = (
                f"The store associated with this group ({type(self.store_path.store)}) "
                "does not support listing, "
                "specifically via the `list_dir` method. "
                "This function requires a store that supports listing."
            )

            raise ValueError(msg)
        # enforce a concurrency limit by passing a semaphore to all the recursive functions
        semaphore = asyncio.Semaphore(config.get("async.concurrency"))
        async for member in _iter_members_deep(
            self,
            max_depth=max_depth,
            skip_keys=skip_keys,
            semaphore=semaphore,
            use_consolidated_for_children=use_consolidated_for_children,
        ):
            yield member

    async def create_hierarchy(
        self,
        nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata],
        *,
        overwrite: bool = False,
    ) -> AsyncIterator[
        tuple[str, AsyncGroup | AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]]
    ]:
        """
        Create a hierarchy of arrays or groups rooted at this group.

        This function will parse its input to ensure that the hierarchy is complete. Any implicit groups
        will be inserted as needed. For example, an input like
        ```{'a/b': GroupMetadata}``` will be parsed to
        ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```.

        Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error
        because this group instance is the root group.

        After input parsing, this function then creates all the nodes in the hierarchy concurrently.

        Arrays and Groups are yielded in the order they are created. This order is not stable and
        should not be relied on.

        Parameters
        ----------
        nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]
            A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy,
            relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that
            all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the
            same hierarchy.

            Leading "/" characters from keys will be removed.
        overwrite : bool
            Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is
            raised instead of overwriting an existing array or group.

            This function will not erase an existing group unless that group is explicitly named in
            ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a
            group already exists at path ``a``, then this function will leave the group at ``a`` as-is.

        Yields
        ------
            tuple[str, AsyncArray | AsyncGroup].
        """
        # check that all the nodes have the same zarr_format as Self
        prefix = self.path
        nodes_parsed = {}
        for key, value in nodes.items():
            if value.zarr_format != self.metadata.zarr_format:
                msg = (
                    "The zarr_format of the nodes must be the same as the parent group. "
                    f"The node at {key} has zarr_format {value.zarr_format}, but the parent group"
                    f" has zarr_format {self.metadata.zarr_format}."
                )
                raise ValueError(msg)
            if normalize_path(key) == "":
                msg = (
                    "The input defines a root node, but a root node already exists, namely this Group instance."
                    "It is an error to use this method to create a root node. "
                    "Remove the root node from the input dict, or use a function like "
                    "create_rooted_hierarchy to create a rooted hierarchy."
                )
                raise ValueError(msg)
            else:
                nodes_parsed[_join_paths([prefix, key])] = value

        async for key, node in create_hierarchy(
            store=self.store,
            nodes=nodes_parsed,
            overwrite=overwrite,
        ):
            if prefix == "":
                out_key = key
            else:
                out_key = key.removeprefix(prefix + "/")
            yield out_key, node

    async def keys(self) -> AsyncGenerator[str, None]:
        """Iterate over member names."""
        async for key, _ in self.members():
            yield key

    async def contains(self, member: str) -> bool:
        """Check if a member exists in the group.

        Parameters
        ----------
        member : str
            Member name.

        Returns
        -------
        bool
        """
        # TODO: this can be made more efficient.
        try:
            await self.getitem(member)
        except KeyError:
            return False
        else:
            return True

    async def groups(self) -> AsyncGenerator[tuple[str, AsyncGroup], None]:
        """Iterate over subgroups."""
        async for name, value in self.members():
            if isinstance(value, AsyncGroup):
                yield name, value

    async def group_keys(self) -> AsyncGenerator[str, None]:
        """Iterate over group names."""
        async for key, _ in self.groups():
            yield key

    async def group_values(self) -> AsyncGenerator[AsyncGroup, None]:
        """Iterate over group values."""
        async for _, group in self.groups():
            yield group

    async def arrays(
        self,
    ) -> AsyncGenerator[
        tuple[str, AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]], None
    ]:
        """Iterate over arrays."""
        async for key, value in self.members():
            if isinstance(value, AsyncArray):
                yield key, value

    async def array_keys(self) -> AsyncGenerator[str, None]:
        """Iterate over array names."""
        async for key, _ in self.arrays():
            yield key

    async def array_values(
        self,
    ) -> AsyncGenerator[AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], None]:
        """Iterate over array values."""
        async for _, array in self.arrays():
            yield array

    async def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
        """
        Return a tree-like representation of a hierarchy.

        This requires the optional ``rich`` dependency.

        Parameters
        ----------
        expand : bool, optional
            This keyword is not yet supported. A NotImplementedError is raised if
            it's used.
        level : int, optional
            The maximum depth below this Group to display in the tree.

        Returns
        -------
        TreeRepr
            A pretty-printable object displaying the hierarchy.
        """
        from zarr.core._tree import group_tree_async

        if expand is not None:
            raise NotImplementedError("'expand' is not yet implemented.")
        return await group_tree_async(self, max_depth=level)

    async def empty(
        self, *, name: str, shape: tuple[int, ...], **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an empty array with the specified shape in this Group. The contents will
        be filled with the array's fill value or zeros if no fill value is provided.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Notes
        -----
        The contents of an empty Zarr array are not defined. On attempting to
        retrieve data from an empty Zarr array, any values may be returned,
        and these are not guaranteed to be stable from one access to the next.
        """
        return await async_api.empty(shape=shape, store=self.store_path, path=name, **kwargs)

    async def zeros(
        self, *, name: str, shape: tuple[int, ...], **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an array, with zero being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.zeros(shape=shape, store=self.store_path, path=name, **kwargs)

    async def ones(
        self, *, name: str, shape: tuple[int, ...], **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an array, with one being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.ones(shape=shape, store=self.store_path, path=name, **kwargs)

    async def full(
        self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

        Parameters
        ----------
        name : str
            Name of the array.
        shape : int or tuple of int
            Shape of the empty array.
        fill_value : scalar
            Value to fill the array with.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.full(
            shape=shape,
            fill_value=fill_value,
            store=self.store_path,
            path=name,
            **kwargs,
        )

    async def empty_like(
        self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create an empty sub-array like `data`. The contents will be filled with
        the array's fill value or zeros if no fill value is provided.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create an empty array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.empty_like(a=data, store=self.store_path, path=name, **kwargs)

    async def zeros_like(
        self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create a sub-array of zeros like `data`.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.zeros_like(a=data, store=self.store_path, path=name, **kwargs)

    async def ones_like(
        self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create a sub-array of ones like `data`.

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.ones_like(a=data, store=self.store_path, path=name, **kwargs)

    async def full_like(
        self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
    ) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
        """Create a sub-array like `data` filled with the `fill_value` of `data` .

        Parameters
        ----------
        name : str
            Name of the array.
        data : array-like
            The array to create the new array like.
        **kwargs
            Keyword arguments passed to [zarr.api.asynchronous.create][].

        Returns
        -------
        AsyncArray
            The new array.
        """
        return await async_api.full_like(a=data, store=self.store_path, path=name, **kwargs)

    async def move(self, source: str, dest: str) -> None:
        """Move a sub-group or sub-array from one path to another.

        Notes
        -----
        Not implemented
        """
        raise NotImplementedError

basename property

basename: str

Final component of name.

info property

info: Any

Return a visual representation of the statically known information about a group.

Note that this doesn't include dynamic information, like the number of child Groups or Arrays.

Returns:

  • GroupInfo

name property

name: str

Group name following h5py convention.

path property

path: str

Storage path.

array_keys async

array_keys() -> AsyncGenerator[str, None]

Iterate over array names.

Source code in zarr/core/group.py
async def array_keys(self) -> AsyncGenerator[str, None]:
    """Iterate over array names."""
    async for key, _ in self.arrays():
        yield key

array_values async

array_values() -> AsyncGenerator[
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata],
    None,
]

Iterate over array values.

Source code in zarr/core/group.py
async def array_values(
    self,
) -> AsyncGenerator[AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata], None]:
    """Iterate over array values."""
    async for _, array in self.arrays():
        yield array

arrays async

arrays() -> AsyncGenerator[
    tuple[
        str,
        AsyncArray[ArrayV2Metadata]
        | AsyncArray[ArrayV3Metadata],
    ],
    None,
]

Iterate over arrays.

Source code in zarr/core/group.py
async def arrays(
    self,
) -> AsyncGenerator[
    tuple[str, AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]], None
]:
    """Iterate over arrays."""
    async for key, value in self.members():
        if isinstance(value, AsyncArray):
            yield key, value

contains async

contains(member: str) -> bool

Check if a member exists in the group.

Parameters:

  • member (str) –

    Member name.

Returns:

Source code in zarr/core/group.py
async def contains(self, member: str) -> bool:
    """Check if a member exists in the group.

    Parameters
    ----------
    member : str
        Member name.

    Returns
    -------
    bool
    """
    # TODO: this can be made more efficient.
    try:
        await self.getitem(member)
    except KeyError:
        return False
    else:
        return True

create_array async

create_array(
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: ndarray[Any, dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an array within this group.

This method lightly wraps zarr.core.array.create_array.

Parameters:

  • name (str) –

    The name of the array relative to the group. If path is None, the array will be located at the root of the store.

  • shape (tuple[int, ...], default: None ) –

    Shape of the array.

  • dtype (DTypeLike, default: None ) –

    Data type of the array.

  • chunks (tuple[int, ...], default: 'auto' ) –

    Chunk shape of the array. If not specified, default are guessed based on the shape and dtype.

  • shards (tuple[int, ...], default: None ) –

    Shard shape of the array. The default value of None results in no sharding at all.

  • filters (Iterable[Codec] | Literal['auto'], default: 'auto' ) –

    Iterable of filters to apply to each chunk of the array, in order, before serializing that chunk to bytes.

    For Zarr format 3, a "filter" is a codec that takes an array and returns an array, and these values must be instances of zarr.abc.codec.ArrayArrayCodec, or a dict representations of zarr.abc.codec.ArrayArrayCodec.

    For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the the order if your filters is consistent with the behavior of each filter.

    The default value of "auto" instructs Zarr to use a default used based on the data type of the array and the Zarr format specified. For all data types in Zarr V3, and most data types in Zarr V2, the default filters are empty. The only cases where default filters are not empty is when the Zarr format is 2, and the data type is a variable-length data type like zarr.dtype.VariableLengthUTF8 or zarr.dtype.VariableLengthUTF8. In these cases, the default filters contains a single element which is a codec specific to that particular data type.

    To create an array with no filters, provide an empty iterable or the value None.

  • compressors (Iterable[Codec], default: 'auto' ) –

    List of compressors to apply to the array. Compressors are applied in order, and after any filters are applied (if any are specified) and the data is serialized into bytes.

    For Zarr format 3, a "compressor" is a codec that takes a bytestream, and returns another bytestream. Multiple compressors my be provided for Zarr format 3. If no compressors are provided, a default set of compressors will be used. These defaults can be changed by modifying the value of array.v3_default_compressors in zarr.config. Use None to omit default compressors.

    For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may be provided for Zarr format 2. If no compressor is provided, a default compressor will be used. in zarr.config. Use None to omit the default compressor.

  • compressor (Codec, default: 'auto' ) –

    Deprecated in favor of compressors.

  • serializer (dict[str, JSON] | ArrayBytesCodec, default: 'auto' ) –

    Array-to-bytes codec to use for encoding the array data. Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion. If no serializer is provided, a default serializer will be used. These defaults can be changed by modifying the value of array.v3_default_serializer in zarr.config.

  • fill_value (Any, default: DEFAULT_FILL_VALUE ) –

    Fill value for the array.

  • order (('C', 'F'), default: "C" ) –

    The memory of the array (default is "C"). For Zarr format 2, this parameter sets the memory order of the array. For Zarr format 3, this parameter is deprecated, because memory order is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory order for Zarr format 3 arrays is via the config parameter, e.g. {'config': 'C'}. If no order is provided, a default order will be used. This default can be changed by modifying the value of array.order in zarr.config.

  • attributes (dict, default: None ) –

    Attributes for the array.

  • chunk_key_encoding (ChunkKeyEncoding, default: None ) –

    A specification of how the chunk keys are represented in storage. For Zarr format 3, the default is {"name": "default", "separator": "/"}}. For Zarr format 2, the default is {"name": "v2", "separator": "."}}.

  • dimension_names (Iterable[str], default: None ) –

    The names of the dimensions (default is None). Zarr format 3 only. Zarr format 2 arrays should not use this parameter.

  • storage_options (dict, default: None ) –

    If using an fsspec URL to create the store, these will be passed to the backend implementation. Ignored otherwise.

  • overwrite (bool, default: False ) –

    Whether to overwrite an array with the same name in the store, if one exists.

  • config (ArrayConfig or ArrayConfigLike, default: None ) –

    Runtime configuration for the array.

  • write_data (bool, default: True ) –

    If a pre-existing array-like object was provided to this function via the data parameter then write_data determines whether the values in that array-like object should be written to the Zarr array created by this function. If write_data is False, then the array will be left empty.

Returns:

Source code in zarr/core/group.py
async def create_array(
    self,
    name: str,
    *,
    shape: ShapeLike | None = None,
    dtype: ZDTypeLike | None = None,
    data: np.ndarray[Any, np.dtype[Any]] | None = None,
    chunks: tuple[int, ...] | Literal["auto"] = "auto",
    shards: ShardsLike | None = None,
    filters: FiltersLike = "auto",
    compressors: CompressorsLike = "auto",
    compressor: CompressorLike = "auto",
    serializer: SerializerLike = "auto",
    fill_value: Any | None = DEFAULT_FILL_VALUE,
    order: MemoryOrder | None = None,
    attributes: dict[str, JSON] | None = None,
    chunk_key_encoding: ChunkKeyEncodingLike | None = None,
    dimension_names: DimensionNames = None,
    storage_options: dict[str, Any] | None = None,
    overwrite: bool = False,
    config: ArrayConfigLike | None = None,
    write_data: bool = True,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an array within this group.

    This method lightly wraps [zarr.core.array.create_array][].

    Parameters
    ----------
    name : str
        The name of the array relative to the group. If ``path`` is ``None``, the array will be located
        at the root of the store.
    shape : tuple[int, ...]
        Shape of the array.
    dtype : npt.DTypeLike
        Data type of the array.
    chunks : tuple[int, ...], optional
        Chunk shape of the array.
        If not specified, default are guessed based on the shape and dtype.
    shards : tuple[int, ...], optional
        Shard shape of the array. The default value of ``None`` results in no sharding at all.
    filters : Iterable[Codec] | Literal["auto"], optional
        Iterable of filters to apply to each chunk of the array, in order, before serializing that
        chunk to bytes.

        For Zarr format 3, a "filter" is a codec that takes an array and returns an array,
        and these values must be instances of [`zarr.abc.codec.ArrayArrayCodec`][], or a
        dict representations of [`zarr.abc.codec.ArrayArrayCodec`][].

        For Zarr format 2, a "filter" can be any numcodecs codec; you should ensure that the
        the order if your filters is consistent with the behavior of each filter.

        The default value of ``"auto"`` instructs Zarr to use a default used based on the data
        type of the array and the Zarr format specified. For all data types in Zarr V3, and most
        data types in Zarr V2, the default filters are empty. The only cases where default filters
        are not empty is when the Zarr format is 2, and the data type is a variable-length data type like
        [`zarr.dtype.VariableLengthUTF8`][] or [`zarr.dtype.VariableLengthUTF8`][]. In these cases,
        the default filters contains a single element which is a codec specific to that particular data type.

        To create an array with no filters, provide an empty iterable or the value ``None``.
    compressors : Iterable[Codec], optional
        List of compressors to apply to the array. Compressors are applied in order, and after any
        filters are applied (if any are specified) and the data is serialized into bytes.

        For Zarr format 3, a "compressor" is a codec that takes a bytestream, and
        returns another bytestream. Multiple compressors my be provided for Zarr format 3.
        If no ``compressors`` are provided, a default set of compressors will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_compressors``
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit default compressors.

        For Zarr format 2, a "compressor" can be any numcodecs codec. Only a single compressor may
        be provided for Zarr format 2.
        If no ``compressor`` is provided, a default compressor will be used.
        in [`zarr.config`][zarr.config].
        Use ``None`` to omit the default compressor.
    compressor : Codec, optional
        Deprecated in favor of ``compressors``.
    serializer : dict[str, JSON] | ArrayBytesCodec, optional
        Array-to-bytes codec to use for encoding the array data.
        Zarr format 3 only. Zarr format 2 arrays use implicit array-to-bytes conversion.
        If no ``serializer`` is provided, a default serializer will be used.
        These defaults can be changed by modifying the value of ``array.v3_default_serializer``
        in [`zarr.config`][zarr.config].
    fill_value : Any, optional
        Fill value for the array.
    order : {"C", "F"}, optional
        The memory of the array (default is "C").
        For Zarr format 2, this parameter sets the memory order of the array.
        For Zarr format 3, this parameter is deprecated, because memory order
        is a runtime parameter for Zarr format 3 arrays. The recommended way to specify the memory
        order for Zarr format 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
        If no ``order`` is provided, a default order will be used.
        This default can be changed by modifying the value of ``array.order`` in [`zarr.config`][zarr.config].
    attributes : dict, optional
        Attributes for the array.
    chunk_key_encoding : ChunkKeyEncoding, optional
        A specification of how the chunk keys are represented in storage.
        For Zarr format 3, the default is ``{"name": "default", "separator": "/"}}``.
        For Zarr format 2, the default is ``{"name": "v2", "separator": "."}}``.
    dimension_names : Iterable[str], optional
        The names of the dimensions (default is None).
        Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
    storage_options : dict, optional
        If using an fsspec URL to create the store, these will be passed to the backend implementation.
        Ignored otherwise.
    overwrite : bool, default False
        Whether to overwrite an array with the same name in the store, if one exists.
    config : ArrayConfig or ArrayConfigLike, optional
        Runtime configuration for the array.
    write_data : bool
        If a pre-existing array-like object was provided to this function via the ``data`` parameter
        then ``write_data`` determines whether the values in that array-like object should be
        written to the Zarr array created by this function. If ``write_data`` is ``False``, then the
        array will be left empty.

    Returns
    -------
    AsyncArray

    """
    compressors = _parse_deprecated_compressor(
        compressor, compressors, zarr_format=self.metadata.zarr_format
    )
    return await create_array(
        store=self.store_path,
        name=name,
        shape=shape,
        dtype=dtype,
        data=data,
        chunks=chunks,
        shards=shards,
        filters=filters,
        compressors=compressors,
        serializer=serializer,
        fill_value=fill_value,
        order=order,
        zarr_format=self.metadata.zarr_format,
        attributes=attributes,
        chunk_key_encoding=chunk_key_encoding,
        dimension_names=dimension_names,
        storage_options=storage_options,
        overwrite=overwrite,
        config=config,
        write_data=write_data,
    )

create_dataset async

create_dataset(
    name: str, *, shape: ShapeLike, **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an array.

Deprecated

AsyncGroup.create_dataset() is deprecated since v3.0.0 and will be removed in v3.1.0. Use AsyncGroup.create_array instead.

Arrays are known as "datasets" in HDF5 terminology. For compatibility with h5py, Zarr groups also implement the zarr.AsyncGroup.require_dataset method.

Parameters:

Returns:

Source code in zarr/core/group.py
@deprecated("Use AsyncGroup.create_array instead.", category=ZarrDeprecationWarning)
async def create_dataset(
    self, name: str, *, shape: ShapeLike, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an array.

    !!! warning "Deprecated"
        `AsyncGroup.create_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
        Use `AsyncGroup.create_array` instead.

    Arrays are known as "datasets" in HDF5 terminology. For compatibility
    with h5py, Zarr groups also implement the [zarr.AsyncGroup.require_dataset][] method.

    Parameters
    ----------
    name : str
        Array name.
    **kwargs : dict
        Additional arguments passed to [zarr.AsyncGroup.create_array][].

    Returns
    -------
    a : AsyncArray
    """
    data = kwargs.pop("data", None)
    # create_dataset in zarr 2.x requires shape but not dtype if data is
    # provided. Allow this configuration by inferring dtype from data if
    # necessary and passing it to create_array
    if "dtype" not in kwargs and data is not None:
        kwargs["dtype"] = data.dtype
    array = await self.create_array(name, shape=shape, **kwargs)
    if data is not None:
        await array.setitem(slice(None), data)
    return array

create_group async

create_group(
    name: str,
    *,
    overwrite: bool = False,
    attributes: dict[str, Any] | None = None,
) -> AsyncGroup

Create a sub-group.

Parameters:

  • name (str) –

    Group name.

  • overwrite (bool, default: False ) –

    If True, do not raise an error if the group already exists.

  • attributes (dict, default: None ) –

    Group attributes.

Returns:

Source code in zarr/core/group.py
async def create_group(
    self,
    name: str,
    *,
    overwrite: bool = False,
    attributes: dict[str, Any] | None = None,
) -> AsyncGroup:
    """Create a sub-group.

    Parameters
    ----------
    name : str
        Group name.
    overwrite : bool, optional
        If True, do not raise an error if the group already exists.
    attributes : dict, optional
        Group attributes.

    Returns
    -------
    g : AsyncGroup
    """
    attributes = attributes or {}
    return await type(self).from_store(
        self.store_path / name,
        attributes=attributes,
        overwrite=overwrite,
        zarr_format=self.metadata.zarr_format,
    )

create_hierarchy async

create_hierarchy(
    nodes: dict[
        str,
        ArrayV2Metadata | ArrayV3Metadata | GroupMetadata,
    ],
    *,
    overwrite: bool = False,
) -> AsyncIterator[
    tuple[
        str,
        AsyncGroup
        | AsyncArray[ArrayV2Metadata]
        | AsyncArray[ArrayV3Metadata],
    ]
]

Create a hierarchy of arrays or groups rooted at this group.

This function will parse its input to ensure that the hierarchy is complete. Any implicit groups will be inserted as needed. For example, an input like {'a/b': GroupMetadata} will be parsed to {'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}.

Explicitly specifying a root group, e.g. with nodes = {'': GroupMetadata()} is an error because this group instance is the root group.

After input parsing, this function then creates all the nodes in the hierarchy concurrently.

Arrays and Groups are yielded in the order they are created. This order is not stable and should not be relied on.

Parameters:

  • nodes (dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]) –

    A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy, relative to the path of the group. The values are instances of GroupMetadata or ArrayMetadata. Note that all values must have the same zarr_format as the parent group -- it is an error to mix zarr versions in the same hierarchy.

    Leading "/" characters from keys will be removed.

  • overwrite (bool, default: False ) –

    Whether to overwrite existing nodes. Defaults to False, in which case an error is raised instead of overwriting an existing array or group.

    This function will not erase an existing group unless that group is explicitly named in nodes. If nodes defines implicit groups, e.g. {`'a/b/c': GroupMetadata}, and a group already exists at path a, then this function will leave the group at a as-is.

Yields:

  • tuple[str, AsyncArray | AsyncGroup].
Source code in zarr/core/group.py
async def create_hierarchy(
    self,
    nodes: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata],
    *,
    overwrite: bool = False,
) -> AsyncIterator[
    tuple[str, AsyncGroup | AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]]
]:
    """
    Create a hierarchy of arrays or groups rooted at this group.

    This function will parse its input to ensure that the hierarchy is complete. Any implicit groups
    will be inserted as needed. For example, an input like
    ```{'a/b': GroupMetadata}``` will be parsed to
    ```{'': GroupMetadata, 'a': GroupMetadata, 'b': Groupmetadata}```.

    Explicitly specifying a root group, e.g. with ``nodes = {'': GroupMetadata()}`` is an error
    because this group instance is the root group.

    After input parsing, this function then creates all the nodes in the hierarchy concurrently.

    Arrays and Groups are yielded in the order they are created. This order is not stable and
    should not be relied on.

    Parameters
    ----------
    nodes : dict[str, GroupMetadata | ArrayV3Metadata | ArrayV2Metadata]
        A dictionary defining the hierarchy. The keys are the paths of the nodes in the hierarchy,
        relative to the path of the group. The values are instances of ``GroupMetadata`` or ``ArrayMetadata``. Note that
        all values must have the same ``zarr_format`` as the parent group -- it is an error to mix zarr versions in the
        same hierarchy.

        Leading "/" characters from keys will be removed.
    overwrite : bool
        Whether to overwrite existing nodes. Defaults to ``False``, in which case an error is
        raised instead of overwriting an existing array or group.

        This function will not erase an existing group unless that group is explicitly named in
        ``nodes``. If ``nodes`` defines implicit groups, e.g. ``{`'a/b/c': GroupMetadata}``, and a
        group already exists at path ``a``, then this function will leave the group at ``a`` as-is.

    Yields
    ------
        tuple[str, AsyncArray | AsyncGroup].
    """
    # check that all the nodes have the same zarr_format as Self
    prefix = self.path
    nodes_parsed = {}
    for key, value in nodes.items():
        if value.zarr_format != self.metadata.zarr_format:
            msg = (
                "The zarr_format of the nodes must be the same as the parent group. "
                f"The node at {key} has zarr_format {value.zarr_format}, but the parent group"
                f" has zarr_format {self.metadata.zarr_format}."
            )
            raise ValueError(msg)
        if normalize_path(key) == "":
            msg = (
                "The input defines a root node, but a root node already exists, namely this Group instance."
                "It is an error to use this method to create a root node. "
                "Remove the root node from the input dict, or use a function like "
                "create_rooted_hierarchy to create a rooted hierarchy."
            )
            raise ValueError(msg)
        else:
            nodes_parsed[_join_paths([prefix, key])] = value

    async for key, node in create_hierarchy(
        store=self.store,
        nodes=nodes_parsed,
        overwrite=overwrite,
    ):
        if prefix == "":
            out_key = key
        else:
            out_key = key.removeprefix(prefix + "/")
        yield out_key, node

delitem async

delitem(key: str) -> None

Delete a group member.

Parameters:

  • key (str) –

    Array or group name

Source code in zarr/core/group.py
async def delitem(self, key: str) -> None:
    """Delete a group member.

    Parameters
    ----------
    key : str
        Array or group name
    """
    store_path = self.store_path / key

    await store_path.delete_dir()
    if self.metadata.consolidated_metadata:
        self.metadata.consolidated_metadata.metadata.pop(key, None)
        await self._save_metadata()

empty async

empty(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an empty array with the specified shape in this Group. The contents will be filled with the array's fill value or zeros if no fill value is provided.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Notes

The contents of an empty Zarr array are not defined. On attempting to retrieve data from an empty Zarr array, any values may be returned, and these are not guaranteed to be stable from one access to the next.

Source code in zarr/core/group.py
async def empty(
    self, *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an empty array with the specified shape in this Group. The contents will
    be filled with the array's fill value or zeros if no fill value is provided.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Notes
    -----
    The contents of an empty Zarr array are not defined. On attempting to
    retrieve data from an empty Zarr array, any values may be returned,
    and these are not guaranteed to be stable from one access to the next.
    """
    return await async_api.empty(shape=shape, store=self.store_path, path=name, **kwargs)

empty_like async

empty_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an empty sub-array like data. The contents will be filled with the array's fill value or zeros if no fill value is provided.

Parameters:

  • name (str) –

    Name of the array.

  • data (array - like) –

    The array to create an empty array like.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def empty_like(
    self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an empty sub-array like `data`. The contents will be filled with
    the array's fill value or zeros if no fill value is provided.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create an empty array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.empty_like(a=data, store=self.store_path, path=name, **kwargs)

full async

full(
    *,
    name: str,
    shape: tuple[int, ...],
    fill_value: Any | None,
    **kwargs: Any,
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • fill_value (scalar) –

    Value to fill the array with.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def full(
    self, *, name: str, shape: tuple[int, ...], fill_value: Any | None, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an array, with "fill_value" being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    fill_value : scalar
        Value to fill the array with.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.full(
        shape=shape,
        fill_value=fill_value,
        store=self.store_path,
        path=name,
        **kwargs,
    )

full_like async

full_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create a sub-array like data filled with the fill_value of data .

Parameters:

  • name (str) –

    Name of the array.

  • data (array - like) –

    The array to create the new array like.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def full_like(
    self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create a sub-array like `data` filled with the `fill_value` of `data` .

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.full_like(a=data, store=self.store_path, path=name, **kwargs)

get async

get(
    key: str, default: DefaultT | None = None
) -> AsyncArray[Any] | AsyncGroup | DefaultT | None

Obtain a group member, returning default if not found.

Parameters:

  • key (str) –

    Group member name.

  • default (object, default: None ) –

    Default value to return if key is not found (default: None).

Returns:

  • object

    Group member (AsyncArray or AsyncGroup) or default if not found.

Source code in zarr/core/group.py
async def get(
    self, key: str, default: DefaultT | None = None
) -> AsyncArray[Any] | AsyncGroup | DefaultT | None:
    """Obtain a group member, returning default if not found.

    Parameters
    ----------
    key : str
        Group member name.
    default : object
        Default value to return if key is not found (default: None).

    Returns
    -------
    object
        Group member (AsyncArray or AsyncGroup) or default if not found.
    """
    try:
        return await self.getitem(key)
    except KeyError:
        return default

getitem async

getitem(
    key: str,
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
    | AsyncGroup
)

Get a subarray or subgroup from the group.

Parameters:

  • key (str) –

    Array or group name

Returns:

Source code in zarr/core/group.py
async def getitem(
    self,
    key: str,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup:
    """
    Get a subarray or subgroup from the group.

    Parameters
    ----------
    key : str
        Array or group name

    Returns
    -------
    AsyncArray or AsyncGroup
    """
    store_path = self.store_path / key
    logger.debug("key=%s, store_path=%s", key, store_path)

    # Consolidated metadata lets us avoid some I/O operations so try that first.
    if self.metadata.consolidated_metadata is not None:
        return self._getitem_consolidated(store_path, key, prefix=self.name)
    try:
        return await get_node(
            store=store_path.store, path=store_path.path, zarr_format=self.metadata.zarr_format
        )
    except FileNotFoundError as e:
        raise KeyError(key) from e

group_keys async

group_keys() -> AsyncGenerator[str, None]

Iterate over group names.

Source code in zarr/core/group.py
async def group_keys(self) -> AsyncGenerator[str, None]:
    """Iterate over group names."""
    async for key, _ in self.groups():
        yield key

group_values async

group_values() -> AsyncGenerator[AsyncGroup, None]

Iterate over group values.

Source code in zarr/core/group.py
async def group_values(self) -> AsyncGenerator[AsyncGroup, None]:
    """Iterate over group values."""
    async for _, group in self.groups():
        yield group

groups async

groups() -> AsyncGenerator[tuple[str, AsyncGroup], None]

Iterate over subgroups.

Source code in zarr/core/group.py
async def groups(self) -> AsyncGenerator[tuple[str, AsyncGroup], None]:
    """Iterate over subgroups."""
    async for name, value in self.members():
        if isinstance(value, AsyncGroup):
            yield name, value

info_complete async

info_complete() -> Any

Return all the information for a group.

This includes dynamic information like the number of child Groups or Arrays. If this group doesn't contain consolidated metadata then this will need to read from the backing Store.

Returns:

  • GroupInfo
Source code in zarr/core/group.py
async def info_complete(self) -> Any:
    """
    Return all the information for a group.

    This includes dynamic information like the number
    of child Groups or Arrays. If this group doesn't contain consolidated
    metadata then this will need to read from the backing Store.

    Returns
    -------
    GroupInfo

    Related
    -------
    [zarr.AsyncGroup.info][]
    """
    members = [x[1].metadata async for x in self.members(max_depth=None)]
    return self._info(members=members)

keys async

keys() -> AsyncGenerator[str, None]

Iterate over member names.

Source code in zarr/core/group.py
async def keys(self) -> AsyncGenerator[str, None]:
    """Iterate over member names."""
    async for key, _ in self.members():
        yield key

members async

members(
    max_depth: int | None = 0,
    *,
    use_consolidated_for_children: bool = True,
) -> AsyncGenerator[
    tuple[
        str,
        AsyncArray[ArrayV2Metadata]
        | AsyncArray[ArrayV3Metadata]
        | AsyncGroup,
    ],
    None,
]

Returns an AsyncGenerator over the arrays and groups contained in this group. This method requires that store_path.store supports directory listing.

The results are not guaranteed to be ordered.

Parameters:

  • max_depth (int, default: 0 ) –

    The maximum number of levels of the hierarchy to include. By default, (max_depth=0) only immediate children are included. Set max_depth=None to include all nodes, and some positive integer to consider children within that many levels of the root Group.

  • use_consolidated_for_children (bool, default: True ) –

    Whether to use the consolidated metadata of child groups loaded from the store. Note that this only affects groups loaded from the store. If the current Group already has consolidated metadata, it will always be used.

Returns:

Source code in zarr/core/group.py
async def members(
    self,
    max_depth: int | None = 0,
    *,
    use_consolidated_for_children: bool = True,
) -> AsyncGenerator[
    tuple[str, AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup],
    None,
]:
    """
    Returns an AsyncGenerator over the arrays and groups contained in this group.
    This method requires that `store_path.store` supports directory listing.

    The results are not guaranteed to be ordered.

    Parameters
    ----------
    max_depth : int, default 0
        The maximum number of levels of the hierarchy to include. By
        default, (``max_depth=0``) only immediate children are included. Set
        ``max_depth=None`` to include all nodes, and some positive integer
        to consider children within that many levels of the root Group.
    use_consolidated_for_children : bool, default True
        Whether to use the consolidated metadata of child groups loaded
        from the store. Note that this only affects groups loaded from the
        store. If the current Group already has consolidated metadata, it
        will always be used.

    Returns
    -------
    path:
        A string giving the path to the target, relative to the Group ``self``.
    value: AsyncArray or AsyncGroup
        The AsyncArray or AsyncGroup that is a child of ``self``.
    """
    if max_depth is not None and max_depth < 0:
        raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead")
    async for item in self._members(
        max_depth=max_depth, use_consolidated_for_children=use_consolidated_for_children
    ):
        yield item

move async

move(source: str, dest: str) -> None

Move a sub-group or sub-array from one path to another.

Notes

Not implemented

Source code in zarr/core/group.py
async def move(self, source: str, dest: str) -> None:
    """Move a sub-group or sub-array from one path to another.

    Notes
    -----
    Not implemented
    """
    raise NotImplementedError

nmembers async

nmembers(max_depth: int | None = 0) -> int

Count the number of members in this group.

Parameters:

  • max_depth (int, default: 0 ) –

    The maximum number of levels of the hierarchy to include. By default, (max_depth=0) only immediate children are included. Set max_depth=None to include all nodes, and some positive integer to consider children within that many levels of the root Group.

Returns:

  • count ( int ) –
Source code in zarr/core/group.py
async def nmembers(
    self,
    max_depth: int | None = 0,
) -> int:
    """Count the number of members in this group.

    Parameters
    ----------
    max_depth : int, default 0
        The maximum number of levels of the hierarchy to include. By
        default, (``max_depth=0``) only immediate children are included. Set
        ``max_depth=None`` to include all nodes, and some positive integer
        to consider children within that many levels of the root Group.

    Returns
    -------
    count : int
    """
    # check if we can use consolidated metadata, which requires that we have non-None
    # consolidated metadata at all points in the hierarchy.
    if self.metadata.consolidated_metadata is not None:
        if max_depth is not None and max_depth < 0:
            raise ValueError(f"max_depth must be None or >= 0. Got '{max_depth}' instead")
        if max_depth is None:
            return len(self.metadata.consolidated_metadata.flattened_metadata)
        else:
            return len(
                [
                    x
                    for x in self.metadata.consolidated_metadata.flattened_metadata
                    if x.count("/") <= max_depth
                ]
            )
    # TODO: consider using aioitertools.builtins.sum for this
    # return await aioitertools.builtins.sum((1 async for _ in self.members()), start=0)
    n = 0
    async for _ in self.members(max_depth=max_depth):
        n += 1
    return n

ones async

ones(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an array, with one being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def ones(
    self, *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an array, with one being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.ones(shape=shape, store=self.store_path, path=name, **kwargs)

ones_like async

ones_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create a sub-array of ones like data.

Parameters:

  • name (str) –

    Name of the array.

  • data (array - like) –

    The array to create the new array like.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def ones_like(
    self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create a sub-array of ones like `data`.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.ones_like(a=data, store=self.store_path, path=name, **kwargs)

open async classmethod

open(
    store: StoreLike,
    zarr_format: ZarrFormat | None = 3,
    use_consolidated: bool | str | None = None,
) -> AsyncGroup

Open a new AsyncGroup

Parameters:

  • store (StoreLike) –
  • zarr_format ((2, 3), default: 2 ) –
  • use_consolidated (bool or str, default: None ) –

    Whether to use consolidated metadata.

    By default, consolidated metadata is used if it's present in the store (in the zarr.json for Zarr format 3 and in the .zmetadata file for Zarr format 2) and the Store supports it.

    To explicitly require consolidated metadata, set use_consolidated=True. In this case, if the Store doesn't support consolidation or consolidated metadata is not found, a ValueError exception is raised.

    To explicitly not use consolidated metadata, set use_consolidated=False, which will fall back to using the regular, non consolidated metadata.

    Zarr format 2 allowed configuring the key storing the consolidated metadata (.zmetadata by default). Specify the custom key as use_consolidated to load consolidated metadata from a non-default key.

Source code in zarr/core/group.py
@classmethod
async def open(
    cls,
    store: StoreLike,
    zarr_format: ZarrFormat | None = 3,
    use_consolidated: bool | str | None = None,
) -> AsyncGroup:
    """Open a new AsyncGroup

    Parameters
    ----------
    store : StoreLike
    zarr_format : {2, 3}, optional
    use_consolidated : bool or str, default None
        Whether to use consolidated metadata.

        By default, consolidated metadata is used if it's present in the
        store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file
        for Zarr format 2) and the Store supports it.

        To explicitly require consolidated metadata, set ``use_consolidated=True``.
        In this case, if the Store doesn't support consolidation or consolidated metadata is
        not found, a ``ValueError`` exception is raised.

        To explicitly *not* use consolidated metadata, set ``use_consolidated=False``,
        which will fall back to using the regular, non consolidated metadata.

        Zarr format 2 allowed configuring the key storing the consolidated metadata
        (``.zmetadata`` by default). Specify the custom key as ``use_consolidated``
        to load consolidated metadata from a non-default key.
    """
    store_path = await make_store_path(store)
    if not store_path.store.supports_consolidated_metadata:
        # Fail if consolidated metadata was requested but the Store doesn't support it
        if use_consolidated:
            store_name = type(store_path.store).__name__
            raise ValueError(
                f"The Zarr store in use ({store_name}) doesn't support consolidated metadata."
            )

        # if use_consolidated was None (optional), the Store dictates it doesn't want consolidation
        use_consolidated = False

    consolidated_key = ZMETADATA_V2_JSON

    if (zarr_format == 2 or zarr_format is None) and isinstance(use_consolidated, str):
        consolidated_key = use_consolidated

    if zarr_format == 2:
        paths = [store_path / ZGROUP_JSON, store_path / ZATTRS_JSON]
        if use_consolidated or use_consolidated is None:
            paths.append(store_path / consolidated_key)

        zgroup_bytes, zattrs_bytes, *rest = await asyncio.gather(
            *[path.get() for path in paths]
        )
        if zgroup_bytes is None:
            raise FileNotFoundError(store_path)

        if use_consolidated or use_consolidated is None:
            maybe_consolidated_metadata_bytes = rest[0]

        else:
            maybe_consolidated_metadata_bytes = None

    elif zarr_format == 3:
        zarr_json_bytes = await (store_path / ZARR_JSON).get()
        if zarr_json_bytes is None:
            raise FileNotFoundError(store_path)
    elif zarr_format is None:
        (
            zarr_json_bytes,
            zgroup_bytes,
            zattrs_bytes,
            maybe_consolidated_metadata_bytes,
        ) = await asyncio.gather(
            (store_path / ZARR_JSON).get(),
            (store_path / ZGROUP_JSON).get(),
            (store_path / ZATTRS_JSON).get(),
            (store_path / str(consolidated_key)).get(),
        )
        if zarr_json_bytes is not None and zgroup_bytes is not None:
            # warn and favor v3
            msg = f"Both zarr.json (Zarr format 3) and .zgroup (Zarr format 2) metadata objects exist at {store_path}. Zarr format 3 will be used."
            warnings.warn(msg, category=ZarrUserWarning, stacklevel=1)
        if zarr_json_bytes is None and zgroup_bytes is None:
            raise FileNotFoundError(
                f"could not find zarr.json or .zgroup objects in {store_path}"
            )
        # set zarr_format based on which keys were found
        if zarr_json_bytes is not None:
            zarr_format = 3
        else:
            zarr_format = 2
    else:
        msg = f"Invalid value for 'zarr_format'. Expected 2, 3, or None. Got '{zarr_format}'."  # type: ignore[unreachable]
        raise MetadataValidationError(msg)

    if zarr_format == 2:
        # this is checked above, asserting here for mypy
        assert zgroup_bytes is not None

        if use_consolidated and maybe_consolidated_metadata_bytes is None:
            # the user requested consolidated metadata, but it was missing
            raise ValueError(consolidated_key)

        elif use_consolidated is False:
            # the user explicitly opted out of consolidated_metadata.
            # Discard anything we might have read.
            maybe_consolidated_metadata_bytes = None

        return cls._from_bytes_v2(
            store_path, zgroup_bytes, zattrs_bytes, maybe_consolidated_metadata_bytes
        )
    else:
        # V3 groups are comprised of a zarr.json object
        assert zarr_json_bytes is not None
        if not isinstance(use_consolidated, bool | None):
            raise TypeError("use_consolidated must be a bool or None for Zarr format 3.")

        return cls._from_bytes_v3(
            store_path,
            zarr_json_bytes,
            use_consolidated=use_consolidated,
        )

require_array async

require_array(
    name: str,
    *,
    shape: ShapeLike,
    dtype: DTypeLike = None,
    exact: bool = False,
    **kwargs: Any,
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Obtain an array, creating if it doesn't exist.

Other kwargs are as per zarr.AsyncGroup.create_dataset.

Parameters:

  • name (str) –

    Array name.

  • shape (int or tuple of ints) –

    Array shape.

  • dtype (str or dtype, default: None ) –

    NumPy dtype.

  • exact (bool, default: False ) –

    If True, require dtype to match exactly. If false, require dtype can be cast from array dtype.

Returns:

Source code in zarr/core/group.py
async def require_array(
    self,
    name: str,
    *,
    shape: ShapeLike,
    dtype: npt.DTypeLike = None,
    exact: bool = False,
    **kwargs: Any,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Obtain an array, creating if it doesn't exist.

    Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][].

    Parameters
    ----------
    name : str
        Array name.
    shape : int or tuple of ints
        Array shape.
    dtype : str or dtype, optional
        NumPy dtype.
    exact : bool, optional
        If True, require `dtype` to match exactly. If false, require
        `dtype` can be cast from array dtype.

    Returns
    -------
    a : AsyncArray
    """
    try:
        ds = await self.getitem(name)
        if not isinstance(ds, AsyncArray):
            raise TypeError(f"Incompatible object ({ds.__class__.__name__}) already exists")

        shape = parse_shapelike(shape)
        if shape != ds.shape:
            raise TypeError(f"Incompatible shape ({ds.shape} vs {shape})")

        dtype = np.dtype(dtype)
        if exact:
            if ds.dtype != dtype:
                raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})")
        else:
            if not np.can_cast(ds.dtype, dtype):
                raise TypeError(f"Incompatible dtype ({ds.dtype} vs {dtype})")
    except KeyError:
        ds = await self.create_array(name, shape=shape, dtype=dtype, **kwargs)

    return ds

require_dataset async

require_dataset(
    name: str,
    *,
    shape: tuple[int, ...],
    dtype: DTypeLike = None,
    exact: bool = False,
    **kwargs: Any,
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Obtain an array, creating if it doesn't exist.

Deprecated

AsyncGroup.require_dataset() is deprecated since v3.0.0 and will be removed in v3.1.0. Use AsyncGroup.require_dataset instead.

Arrays are known as "datasets" in HDF5 terminology. For compatibility with h5py, Zarr groups also implement the zarr.AsyncGroup.create_dataset method.

Other kwargs are as per zarr.AsyncGroup.create_dataset.

Parameters:

  • name (str) –

    Array name.

  • shape (int or tuple of ints) –

    Array shape.

  • dtype (str or dtype, default: None ) –

    NumPy dtype.

  • exact (bool, default: False ) –

    If True, require dtype to match exactly. If false, require dtype can be cast from array dtype.

Returns:

Source code in zarr/core/group.py
@deprecated("Use AsyncGroup.require_array instead.", category=ZarrDeprecationWarning)
async def require_dataset(
    self,
    name: str,
    *,
    shape: tuple[int, ...],
    dtype: npt.DTypeLike = None,
    exact: bool = False,
    **kwargs: Any,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Obtain an array, creating if it doesn't exist.

    !!! warning "Deprecated"
        `AsyncGroup.require_dataset()` is deprecated since v3.0.0 and will be removed in v3.1.0.
        Use `AsyncGroup.require_dataset` instead.

    Arrays are known as "datasets" in HDF5 terminology. For compatibility
    with h5py, Zarr groups also implement the [zarr.AsyncGroup.create_dataset][] method.

    Other `kwargs` are as per [zarr.AsyncGroup.create_dataset][].

    Parameters
    ----------
    name : str
        Array name.
    shape : int or tuple of ints
        Array shape.
    dtype : str or dtype, optional
        NumPy dtype.
    exact : bool, optional
        If True, require `dtype` to match exactly. If false, require
        `dtype` can be cast from array dtype.

    Returns
    -------
    a : AsyncArray
    """
    return await self.require_array(name, shape=shape, dtype=dtype, exact=exact, **kwargs)

require_group async

require_group(
    name: str, overwrite: bool = False
) -> AsyncGroup

Obtain a sub-group, creating one if it doesn't exist.

Parameters:

  • name (str) –

    Group name.

  • overwrite (bool, default: False ) –

    Overwrite any existing group with given name if present.

Returns:

Source code in zarr/core/group.py
async def require_group(self, name: str, overwrite: bool = False) -> AsyncGroup:
    """Obtain a sub-group, creating one if it doesn't exist.

    Parameters
    ----------
    name : str
        Group name.
    overwrite : bool, optional
        Overwrite any existing group with given `name` if present.

    Returns
    -------
    g : AsyncGroup
    """
    if overwrite:
        # TODO: check that overwrite=True errors if an array exists where the group is being created
        grp = await self.create_group(name, overwrite=True)
    else:
        try:
            item: (
                AsyncGroup | AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]
            ) = await self.getitem(name)
            if not isinstance(item, AsyncGroup):
                raise TypeError(
                    f"Incompatible object ({item.__class__.__name__}) already exists"
                )
            assert isinstance(item, AsyncGroup)  # make mypy happy
            grp = item
        except KeyError:
            grp = await self.create_group(name)
    return grp

require_groups async

require_groups(*names: str) -> tuple[AsyncGroup, ...]

Convenience method to require multiple groups in a single call.

Parameters:

  • *names (str, default: () ) –

    Group names.

Returns:

Source code in zarr/core/group.py
async def require_groups(self, *names: str) -> tuple[AsyncGroup, ...]:
    """Convenience method to require multiple groups in a single call.

    Parameters
    ----------
    *names : str
        Group names.

    Returns
    -------
    Tuple[AsyncGroup, ...]
    """
    if not names:
        return ()
    return tuple(await asyncio.gather(*(self.require_group(name) for name in names)))

setitem async

setitem(key: str, value: Any) -> None

Fastpath for creating a new array New arrays will be created with default array settings for the array type.

Parameters:

  • key (str) –

    Array name

  • value (array - like) –

    Array data

Source code in zarr/core/group.py
async def setitem(self, key: str, value: Any) -> None:
    """
    Fastpath for creating a new array
    New arrays will be created with default array settings for the array type.

    Parameters
    ----------
    key : str
        Array name
    value : array-like
        Array data
    """
    path = self.store_path / key
    await async_api.save_array(
        store=path, arr=value, zarr_format=self.metadata.zarr_format, overwrite=True
    )

tree async

tree(
    expand: bool | None = None, level: int | None = None
) -> Any

Return a tree-like representation of a hierarchy.

This requires the optional rich dependency.

Parameters:

  • expand (bool, default: None ) –

    This keyword is not yet supported. A NotImplementedError is raised if it's used.

  • level (int, default: None ) –

    The maximum depth below this Group to display in the tree.

Returns:

  • TreeRepr

    A pretty-printable object displaying the hierarchy.

Source code in zarr/core/group.py
async def tree(self, expand: bool | None = None, level: int | None = None) -> Any:
    """
    Return a tree-like representation of a hierarchy.

    This requires the optional ``rich`` dependency.

    Parameters
    ----------
    expand : bool, optional
        This keyword is not yet supported. A NotImplementedError is raised if
        it's used.
    level : int, optional
        The maximum depth below this Group to display in the tree.

    Returns
    -------
    TreeRepr
        A pretty-printable object displaying the hierarchy.
    """
    from zarr.core._tree import group_tree_async

    if expand is not None:
        raise NotImplementedError("'expand' is not yet implemented.")
    return await group_tree_async(self, max_depth=level)

update_attributes async

update_attributes(
    new_attributes: dict[str, Any],
) -> AsyncGroup

Update group attributes.

Parameters:

  • new_attributes (dict) –

    New attributes to set on the group.

Returns:

Source code in zarr/core/group.py
async def update_attributes(self, new_attributes: dict[str, Any]) -> AsyncGroup:
    """Update group attributes.

    Parameters
    ----------
    new_attributes : dict
        New attributes to set on the group.

    Returns
    -------
    self : AsyncGroup
    """
    self.metadata.attributes.update(new_attributes)

    # Write new metadata
    await self._save_metadata()

    return self

zeros async

zeros(
    *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create an array, with zero being used as the default value for uninitialized portions of the array.

Parameters:

  • name (str) –

    Name of the array.

  • shape (int or tuple of int) –

    Shape of the empty array.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def zeros(
    self, *, name: str, shape: tuple[int, ...], **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create an array, with zero being used as the default value for uninitialized portions of the array.

    Parameters
    ----------
    name : str
        Name of the array.
    shape : int or tuple of int
        Shape of the empty array.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.zeros(shape=shape, store=self.store_path, path=name, **kwargs)

zeros_like async

zeros_like(
    *, name: str, data: ArrayLike, **kwargs: Any
) -> (
    AsyncArray[ArrayV2Metadata]
    | AsyncArray[ArrayV3Metadata]
)

Create a sub-array of zeros like data.

Parameters:

  • name (str) –

    Name of the array.

  • data (array - like) –

    The array to create the new array like.

  • **kwargs (Any, default: {} ) –

    Keyword arguments passed to zarr.api.asynchronous.create.

Returns:

Source code in zarr/core/group.py
async def zeros_like(
    self, *, name: str, data: async_api.ArrayLike, **kwargs: Any
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
    """Create a sub-array of zeros like `data`.

    Parameters
    ----------
    name : str
        Name of the array.
    data : array-like
        The array to create the new array like.
    **kwargs
        Keyword arguments passed to [zarr.api.asynchronous.create][].

    Returns
    -------
    AsyncArray
        The new array.
    """
    return await async_api.zeros_like(a=data, store=self.store_path, path=name, **kwargs)