I subclassed from StringIO to create a MockFile-class. There should be an Attribute “name” in the derived class, but creating this Attribute throws an AttributeError.
Puzzled i did a __dict__ lookup and found that there was already a name-key. Iterating through the __mro__ i found a property named ‘name‘, obviously read-only in theio.TextIOWrapper class.
So i have basically two Questions:
- for what is this ‘name’ property intended
- is it safe to overwrite it with a
settattrassignment?
The example-code for completness:
class MockFile(StringIO):
def __init__(self, name, buffer_ = None):
super(MockFile, self).__init__(buffer_)
self.name = name
>>> mfile = MockFile('stringio.tmp', u'#MockFile')
leads to:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
AttributeError: can't set attribute
The
nameproperty ofio.StringIOin Python 2.6 comes from the class hierarchy in theiomodule. It’s a somewhat complex setup with both inheritance and composition, and thenameproperty is used to propagate names from underlying objects to the various wrappers and specializations. The actual property onio.StringIOis gone in Python 2.7 and later, though, so you should be fine to shadow it in your subclass.You can’t use
setattr()to set the property any more than actual assignment —settattr()and attribute assignment both work the same way. The nature of property prevents you from shadowing the baseclass property with an instance attribute (without doing more.) You can, however, define a property of your own with the same name, or trick Python into not seeing the property in the first place: