[lxml-dev] adding __float__, __int__ etc. to objectify.StringElement
jholg at gmx.de
jholg at gmx.de
Mon Apr 7 15:33:07 CEST 2008
Hi,
Checked in as revision 53527:
$ svn diff -r 53526
Index: src/lxml/tests/test_objectify.py
===================================================================
--- src/lxml/tests/test_objectify.py (revision 53526)
+++ src/lxml/tests/test_objectify.py (working copy)
@@ -815,7 +815,27 @@
el = objectify.DataElement(s)
val = 5
self.assertRaises(TypeError, el.__mod__, val)
+
+ def test_type_str_as_int(self):
+ v = "1"
+ el = objectify.DataElement(v)
+ self.assertEquals(int(el), 1)
+ def test_type_str_as_long(self):
+ v = "1"
+ el = objectify.DataElement(v)
+ self.assertEquals(long(el), 1)
+
+ def test_type_str_as_float(self):
+ v = "1"
+ el = objectify.DataElement(v)
+ self.assertEquals(float(el), 1)
+
+ def test_type_str_as_complex(self):
+ v = "1"
+ el = objectify.DataElement(v)
+ self.assertEquals(complex(el), 1)
+
def test_type_str_mod_data_elements(self):
s = "%d %f %s %r"
el = objectify.DataElement(s)
Index: src/lxml/lxml.objectify.pyx
===================================================================
--- src/lxml/lxml.objectify.pyx (revision 53526)
+++ src/lxml/lxml.objectify.pyx (working copy)
@@ -773,6 +773,18 @@
def __mod__(self, other):
return _strValueOf(self) % other
+ def __int__(self):
+ return int(textOf(self._c_node))
+
+ def __long__(self):
+ return long(textOf(self._c_node))
+
+ def __float__(self):
+ return float(textOf(self._c_node))
+
+ def __complex__(self):
+ return complex(textOf(self._c_node))
+
cdef class NoneElement(ObjectifiedDataElement):
def __str__(self):
return "None"
> You mean because of the int/bool duality in Python, but I don't think
that's
> something we should easily enable without a compelling use case. Remember
that
> it would mean converting the string value "true" to int(1), I don't think
> that's obvious behaviour.
Yes, I was referring to that:
>>> int(True)
1
>>> float(True)
1.0
>>> long(True)
1L
>>> complex
<type 'complex'>
>>> complex(True)
(1+0j)
>>>
I actually wasn't aware of that behaviour of Python booleans.
And this is definitely no priority for me. Then again, one could argue
that BoolElement should behave as much as a native bool in Python,
only that its XML representation is the string value "true".
And there are already subtleties for BoolElement:
>>> root = etree.fromstring("<root><x>true</x></root>")
>>> type(root.x)
<type 'lxml.objectify.BoolElement'>
>>> root.x.text
'true'
>>> str(root.x)
'True'
>>>
Cheers,
Holger
--
Psssst! Schon vom neuen GMX MultiMessenger gehört?
Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codespeak.net/pipermail/lxml-dev/attachments/20080407/f181fae2/attachment.htm
More information about the lxml-dev
mailing list