Unable to set attributes in instance of ElementTree.Element in Python 3

I don't understand why in Python 3 I cannot add some attributes to instances ElementTree.Element. Here is the difference:

In Python 2:

Python 2.6.6 (r266:84292, Jun 18 2012, 14:18:47) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree import ElementTree as ET
>>> el = ET.Element('table')
>>> el.foo = 50
>>> el.foo
50
>>> 

In Python 3:

Python 3.3.0 (default, Sep 11 2013, 16:29:08) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree import ElementTree as ET
>>> el = ET.Element('table')
>>> el.foo = 50
>>> el.foo
AttributeError: foo
>>> 

Python 2 is provided by the distribution kit (CentOS). Python 3 was compiled from sources.

Is this the intended behavior, bug, or do I need to recompile python 3 with some additional flags?

UPDATE

Some clarification: I am trying to set attributes on a Python object, i.e. on an instance Element. Not XML Attributes ( Element.attrib).

This problem arose when I tried to subclass Element. Here is an example:

>>> class Table(ET.Element):
...     def __init__(self):
...         super().__init__('table')
...         print('calling __init__')
...         self.foo = 50
... 
>>> t = Table()
calling __init__
>>> t.foo
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'foo'
>>> 

It makes me think that the class Elementis being created in some complicated way, but I cannot understand what is going on. Hence the question.

+4
3

, ... . ElementTree, dict , .

, ... python XML? , :

el = ET.Element('table')
el.set('foo', 50) 
#or
el.attrib['foo'] = 50

python, , , Element/SubElement "" .

6/4/2016: , , , , ( python 2.7):

class Table(ET.Element):
    # Adding __slots__ gives it a known attribute to use    
    __slots__ = ('foo',)
    def __init__(self):
        super().__init__('table')
        print('calling __init__')
        self.foo = 50
+1

3.3 ElementTree c , . , Set Get , ET._Element_Py, Python.

+1

Python 3, , :

>>> from xml.etree import ElementTree as ET
>>> el = ET.Element('table')
>>> el.set("foo", 50)
>>> el.get("foo")
50
>>> el.attrib
{"foo": 50}

Python 2.X, , , .

, Python bug tracker, .

0

All Articles