Skip to content

Commit a039414

Browse files
committed
feat: add get_root
1 parent a41287f commit a039414

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/pystac/stac_object.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
if TYPE_CHECKING:
2424
from .catalog import Catalog
25+
from .container import Container
2526
from .io import Read, Write
2627

2728

@@ -82,7 +83,7 @@ def from_dict(
8283
d: dict[str, Any],
8384
*,
8485
href: str | None = None,
85-
root: Catalog | None = None, # TODO deprecation warning
86+
root: Catalog | None = None,
8687
migrate: bool = False,
8788
preserve_dict: bool = True, # TODO deprecation warning
8889
reader: Read | None = None,
@@ -127,6 +128,15 @@ def from_dict(
127128
raise StacError(f"unknown type field: {type_value}")
128129

129130
if isinstance(stac_object, cls):
131+
if root:
132+
warnings.warn(
133+
"The `root` argument is deprecated in PySTAC v2 and "
134+
"will be removed in a future version. Prefer to use "
135+
"`stac_object.set_link(Link.root(catalog))` "
136+
"after object creation.",
137+
FutureWarning,
138+
)
139+
stac_object.set_link(Link.root(root))
130140
return stac_object
131141
else:
132142
raise PystacError(f"Expected {cls} but got a {type(stac_object)}")
@@ -244,6 +254,19 @@ def save_object(
244254
else:
245255
raise PystacError("cannot save an object without an href")
246256

257+
def get_root(self) -> Container | None:
258+
"""Returns the container at this object's root link, if there is one."""
259+
from .container import Container
260+
261+
if link := self.get_link(ROOT_REL):
262+
stac_object = link.get_stac_object()
263+
if isinstance(stac_object, Container):
264+
return stac_object
265+
else:
266+
return None
267+
else:
268+
return None
269+
247270
def get_link(self, rel: str) -> Link | None:
248271
return next((link for link in self._links if link.rel == rel), None)
249272

tests/v1/test_item.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
from copy import deepcopy
22
from typing import Any
33

4-
from pystac import Item
4+
import pytest
5+
6+
from pystac import Catalog, Item
57

68
from . import utils
79

@@ -26,3 +28,10 @@ def test_to_from_dict(sample_item_dict: dict[str, Any]) -> None:
2628
# assert that the parameter is preserved regardless of preserve_dict
2729
Item.from_dict(param_dict, preserve_dict=False)
2830
assert param_dict == sample_item_dict
31+
32+
33+
def test_from_dict_set_root(sample_item_dict: dict[str, Any]) -> None:
34+
catalog = Catalog(id="test", description="test desc")
35+
with pytest.warns(FutureWarning):
36+
item = Item.from_dict(sample_item_dict, root=catalog)
37+
assert item.get_root() is catalog

0 commit comments

Comments
 (0)