From 932c6be0febd98c09222464ed3859847656c8672 Mon Sep 17 00:00:00 2001 From: David Mandelberg Date: Wed, 25 Oct 2023 00:11:47 -0400 Subject: [PATCH] Add a function to parse an Item from its canonical URI SPARQL results seem to be in this form. --- rock_paper_sand/wikidata_value.py | 7 +++++++ rock_paper_sand/wikidata_value_test.py | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/rock_paper_sand/wikidata_value.py b/rock_paper_sand/wikidata_value.py index e10552c..b67248b 100644 --- a/rock_paper_sand/wikidata_value.py +++ b/rock_paper_sand/wikidata_value.py @@ -85,6 +85,13 @@ def uri(self) -> str: """ return f"{_ITEM_PREFIX_CANONICAL_URI}{self.id}" + @classmethod + def from_uri(cls, value: str) -> Self: + """Returns the item parsed from its canonical URI.""" + return cls( + _parse_id(value, prefixes=(_ITEM_PREFIX_CANONICAL_URI,), letter="Q") + ) + _i = Item.from_string Q_GREGORIAN_CALENDAR = _i("https://www.wikidata.org/wiki/Q12138") diff --git a/rock_paper_sand/wikidata_value_test.py b/rock_paper_sand/wikidata_value_test.py index 8062839..49b93d0 100644 --- a/rock_paper_sand/wikidata_value_test.py +++ b/rock_paper_sand/wikidata_value_test.py @@ -55,6 +55,18 @@ def test_item_uri(self) -> None: wikidata_value.Item("Q1").uri, ) + def test_item_from_uri_invalid(self) -> None: + with self.assertRaisesRegex(ValueError, "Wikidata IRI or ID"): + wikidata_value.Item.from_uri("Q1") + + def test_item_from_uri_valid(self) -> None: + self.assertEqual( + "Q1", + wikidata_value.Item.from_uri( + "http://www.wikidata.org/entity/Q1" + ).id, + ) + def test_invalid_property_id(self) -> None: with self.assertRaisesRegex(ValueError, "Wikidata IRI or ID"): wikidata_value.Property("foo")