Skip to content

Commit 4ad4bf6

Browse files
committed
Return calling class from Asset constructors
1 parent 44157ab commit 4ad4bf6

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

pystac/asset.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,8 @@ def clone(self) -> "Asset":
127127
Returns:
128128
Asset: The clone of this asset.
129129
"""
130-
return Asset(
130+
cls = self.__class__
131+
return cls(
131132
href=self.href,
132133
title=self.title,
133134
description=self.description,
@@ -139,8 +140,8 @@ def clone(self) -> "Asset":
139140
def __repr__(self) -> str:
140141
return "<Asset href={}>".format(self.href)
141142

142-
@staticmethod
143-
def from_dict(d: Dict[str, Any]) -> "Asset":
143+
@classmethod
144+
def from_dict(cls, d: Dict[str, Any]) -> "Asset":
144145
"""Constructs an Asset from a dict.
145146
146147
Returns:
@@ -156,7 +157,7 @@ def from_dict(d: Dict[str, Any]) -> "Asset":
156157
if any(d):
157158
properties = d
158159

159-
return Asset(
160+
return cls(
160161
href=href,
161162
media_type=media_type,
162163
title=title,

tests/test_item.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,3 +742,26 @@ def test_from_file_returns_subclass(self) -> None:
742742
custom_item = self.BasicCustomItem.from_file(self.SAMPLE_ITEM)
743743

744744
self.assertIsInstance(custom_item, self.BasicCustomItem)
745+
746+
747+
class AssetSubClassTest(unittest.TestCase):
748+
class CustomAsset(Asset):
749+
pass
750+
751+
def setUp(self) -> None:
752+
self.maxDiff = None
753+
with open(TestCases.get_path("data-files/item/sample-item.json")) as src:
754+
item_dict = json.load(src)
755+
756+
self.asset_dict = item_dict["assets"]["analytic"]
757+
758+
def test_from_dict(self) -> None:
759+
asset = self.CustomAsset.from_dict(self.asset_dict)
760+
761+
self.assertIsInstance(asset, self.CustomAsset)
762+
763+
def test_clone(self) -> None:
764+
asset = self.CustomAsset.from_dict(self.asset_dict)
765+
cloned_asset = asset.clone()
766+
767+
self.assertIsInstance(cloned_asset, self.CustomAsset)

0 commit comments

Comments
 (0)