jenkins-bot has submitted this change and it was merged.

Change subject: Support unit-less quantity values
......................................................................


Support unit-less quantity values

The class WbQuantity works similar to WbTime. Currently only unit-less
quantities are supported.

Values are being 'converted' the way the API expects resp. responds.

Change-Id: I0a81f8c17f5f5b1b977f4d8054acb5a0574816e1
---
M pywikibot/__init__.py
M pywikibot/page.py
M tests/wikibase_tests.py
3 files changed, 71 insertions(+), 0 deletions(-)

Approvals:
  Merlijn van Deen: Looks good to me, approved
  jenkins-bot: Verified



diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index ff2f61a..1709b0e 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -313,6 +313,64 @@
             u"timezone=%(timezone)d, calendarmodel='%(calendarmodel)s')" % 
self.__dict__
 
 
+class WbQuantity(object):
+    """ A Wikibase quantity representation"""
+
+    def __init__(self, amount, unit=None, error=None):
+        """
+        Creates a new WbQuantity object. The amount is a number representing
+        this quantity. The unit is currently not used (only unit-less
+        quantities are supported). The error is a number indicating the
+        uncertainty of the amount (e.g. ±1). Alternatively the error can be
+        expressed as a tuple, where the first value is the upper error and the
+        second is the lower error value.
+        """
+        if amount is None:
+            raise ValueError('no amount given')
+        if unit is not None and unit != '1':
+            raise NotImplementedError('Currently only unit-less quantities are 
supported')
+        if unit is None:
+            unit = '1'
+        self.amount = long(amount)
+        self.unit = unit
+        upperError = lowerError = 0
+        if isinstance(error, tuple):
+            upperError, lowerError = error
+        elif error is not None:
+            upperError = lowerError = error
+        self.upperBound = self.amount + upperError
+        self.lowerBound = self.amount - lowerError
+
+    def toWikibase(self):
+        """
+        Function which converts the data to a JSON object
+        for the Wikibase API.
+        """
+        json = {'amount': self.amount,
+                'upperBound': self.upperBound,
+                'lowerBound': self.lowerBound,
+                'unit': self.unit
+                }
+        return json
+
+    @staticmethod
+    def fromWikibase(wb):
+        amount = long(wb[u'amount'])
+        upperBound = long(wb[u'upperBound'])
+        lowerBound = long(wb[u'lowerBound'])
+        error = (upperBound - amount, amount - lowerBound)
+        return WbQuantity(amount, wb[u'unit'], error)
+
+    def __str__(self):
+        return str(self.toWikibase())
+
+    def __eq__(self, other):
+        return self.__dict__ == other.__dict__
+
+    def __repr__(self):
+        return u"WbQuantity(amount=%(amount)d, upperBound=%(upperBound)d, 
lowerBound=%(lowerBound)d, unit=%(unit)s" % self.__dict__
+
+
 def deprecated(instead=None):
     """Decorator to output a method deprecation warning.
 
diff --git a/pywikibot/page.py b/pywikibot/page.py
index fe54ef6..b69d3d1 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -2886,6 +2886,9 @@
             elif claim.getType() == 'time':
                 claim.target = pywikibot.WbTime.fromWikibase(
                     data['mainsnak']['datavalue']['value'])
+            elif claim.getType() == 'quantity':
+                claim.target = pywikibot.WbQuantity.fromWikibase(
+                    data['mainsnak']['datavalue']['value'])
             else:
                 # This covers string, url types
                 claim.target = data['mainsnak']['datavalue']['value']
@@ -3069,6 +3072,8 @@
             value = self.getTarget().toWikibase()
         elif self.getType() == 'time':
             value = self.getTarget().toWikibase()
+        elif self.getType() == 'quantity':
+            value = self.getTarget().toWikibase()
         else:
             raise NotImplementedError('%s datatype is not supported yet.'
                                       % self.getType())
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index 4b6af74..5183b46 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -52,6 +52,14 @@
         self.assertRaises(ValueError, pywikibot.WbTime, site=wikidata, 
precision=15)
         self.assertRaises(ValueError, pywikibot.WbTime, site=wikidata, 
precision='invalid_precision')
 
+        # test WbQuantity
+        q = pywikibot.WbQuantity(amount=1234, error=1)
+        self.assertEqual(q.toWikibase(), {'amount': 1234, 'lowerBound': 1233, 
'upperBound': 1235, 'unit': '1', })
+        q = pywikibot.WbQuantity(amount=5, error=(2, 3))
+        self.assertEqual(q.toWikibase(), {'amount': 5, 'lowerBound': 2, 
'upperBound': 7, 'unit': '1', })
+        self.assertRaises(ValueError, pywikibot.WbQuantity, amount=None, 
error=1)
+        self.assertRaises(NotImplementedError, pywikibot.WbQuantity, 
amount=789, unit='invalid_unit')
+
         # test WikibasePage.__cmp__
         self.assertEqual(pywikibot.ItemPage.fromPage(mainpage), 
pywikibot.ItemPage(repo, 'q5296'))
 

-- 
To view, visit https://gerrit.wikimedia.org/r/132629
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: I0a81f8c17f5f5b1b977f4d8054acb5a0574816e1
Gerrit-PatchSet: 8
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Metaodi <[email protected]>
Gerrit-Reviewer: Ladsgroup <[email protected]>
Gerrit-Reviewer: Legoktm <[email protected]>
Gerrit-Reviewer: Merlijn van Deen <[email protected]>
Gerrit-Reviewer: Metaodi <[email protected]>
Gerrit-Reviewer: Mpaa <[email protected]>
Gerrit-Reviewer: Ricordisamoa <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to