jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1176818?usp=email )
Change subject: fix: improve WbRepresentation __hash__, __repr__ and remove
__ne__
......................................................................
fix: improve WbRepresentation __hash__, __repr__ and remove __ne__
- Use json.dumps(..., sort_keys=True) in __hash__ to handle nested dicts
from toWikibase(), ensuring consistent hashability.
- Simplify __repr__ and use repr for attributes
- Remove __ne__ method; Python 3 derives it automatically from __eq__.
- update tests
Change-Id: I710b4d106aef5c5c6459019d4564cfecb8555658
---
M pywikibot/_wbtypes.py
M tests/wbtypes_tests.py
2 files changed, 43 insertions(+), 31 deletions(-)
Approvals:
jenkins-bot: Verified
Xqt: Looks good to me, approved
diff --git a/pywikibot/_wbtypes.py b/pywikibot/_wbtypes.py
index eb15038..e3ed6b0 100644
--- a/pywikibot/_wbtypes.py
+++ b/pywikibot/_wbtypes.py
@@ -51,7 +51,7 @@
@abc.abstractmethod
def __init__(self) -> None:
- """Constructor."""
+ """Initializer."""
raise NotImplementedError
@abc.abstractmethod
@@ -70,28 +70,37 @@
raise NotImplementedError
def __str__(self) -> str:
- return json.dumps(self.toWikibase(), indent=4, sort_keys=True,
- separators=(',', ': '))
+ return json.dumps(
+ self.toWikibase(),
+ indent=4,
+ sort_keys=True,
+ separators=(',', ': ')
+ )
def __repr__(self) -> str:
+ """String representation of this object.
+
+ .. versionchanged:: 10.4
+ Parameters are shown as representations instead of plain
+ strings.
+
+ :meta public:
+ """
assert isinstance(self._items, tuple)
assert all(isinstance(item, str) for item in self._items)
- values = ((attr, getattr(self, attr)) for attr in self._items)
- attrs = ', '.join(f'{attr}={value}'
- for attr, value in values)
- return f'{self.__class__.__name__}({attrs})'
+ attrs = ', '.join(f'{attr}={getattr(self, attr)!r}'
+ for attr in self._items)
+ return f'{type(self).__name__}({attrs})'
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
return self.toWikibase() == other.toWikibase()
+
return NotImplemented
def __hash__(self) -> int:
- return hash(frozenset(self.toWikibase().items()))
-
- def __ne__(self, other: object) -> bool:
- return not self.__eq__(other)
+ return hash(json.dumps(self.toWikibase(), sort_keys=True))
class Coordinate(WbRepresentation):
diff --git a/tests/wbtypes_tests.py b/tests/wbtypes_tests.py
index a136ba6..95ce78b 100755
--- a/tests/wbtypes_tests.py
+++ b/tests/wbtypes_tests.py
@@ -634,18 +634,20 @@
def test_WbQuantity_formatting_bound(self) -> None:
"""Test WbQuantity formatting with bounds."""
repo = self.get_repo()
- q = pywikibot.WbQuantity(amount='0.044405586', error='0', site=repo)
+ amount = '0.044405586'
+ repr_amount = repr(Decimal(amount))
+ q = pywikibot.WbQuantity(amount=amount, error='0', site=repo)
self.assertEqual(str(q),
- '{{\n'
- ' "amount": "+{val}",\n'
- ' "lowerBound": "+{val}",\n'
- ' "unit": "1",\n'
- ' "upperBound": "+{val}"\n'
- '}}'.format(val='0.044405586'))
+ f'{{\n'
+ f' "amount": "+{amount}",\n'
+ f' "lowerBound": "+{amount}",\n'
+ f' "unit": "1",\n'
+ f' "upperBound": "+{amount}"\n'
+ f'}}')
self.assertEqual(repr(q),
- 'WbQuantity(amount={val}, '
- 'upperBound={val}, lowerBound={val}, '
- 'unit=1)'.format(val='0.044405586'))
+ f'WbQuantity(amount={repr_amount}, '
+ f'upperBound={repr_amount}, '
+ f"lowerBound={repr_amount}, unit='1')")
def test_WbQuantity_self_equality(self) -> None:
"""Test WbQuantity equality."""
@@ -717,18 +719,19 @@
def test_WbQuantity_formatting_unbound(self) -> None:
"""Test WbQuantity formatting without bounds."""
- q = pywikibot.WbQuantity(amount='0.044405586', site=self.repo)
+ amount = '0.044405586'
+ q = pywikibot.WbQuantity(amount=amount, site=self.repo)
self.assertEqual(str(q),
- '{{\n'
- ' "amount": "+{val}",\n'
- ' "lowerBound": null,\n'
- ' "unit": "1",\n'
- ' "upperBound": null\n'
- '}}'.format(val='0.044405586'))
+ f'{{\n'
+ f' "amount": "+{amount}",\n'
+ f' "lowerBound": null,\n'
+ f' "unit": "1",\n'
+ f' "upperBound": null\n'
+ f'}}')
self.assertEqual(repr(q),
- 'WbQuantity(amount={val}, '
- 'upperBound=None, lowerBound=None, '
- 'unit=1)'.format(val='0.044405586'))
+ f'WbQuantity(amount={Decimal(amount)!r}, '
+ f'upperBound=None, lowerBound=None, '
+ f"unit='1')")
def test_WbQuantity_fromWikibase_unbound(self) -> None:
"""Test WbQuantity.fromWikibase() instantiating without bounds."""
--
To view, visit
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1176818?usp=email
To unsubscribe, or for help writing mail filters, visit
https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I710b4d106aef5c5c6459019d4564cfecb8555658
Gerrit-Change-Number: 1176818
Gerrit-PatchSet: 5
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
Gerrit-CC: Matěj Suchánek <[email protected]>
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]