Inactivist
Inactivist

Reputation: 10457

Setting a property on a list object in Python 2.7

Consider this bit of Python code:

>>> l = [1,2,3]
>>> l.foo = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'
>>> setattr(l, 'foo', 'bar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'

I understand why this doesn't work -- list has no __dict__ hence it doesn't support attributes.

I'd like to know if there are recommended alternative list collection classes supporting custom properties, or, if there's a good Pythonic 'hack' available to add this to the standard list class.

Or is this a case where it's simpler to roll your own?

Upvotes: 1

Views: 331

Answers (2)

kiriloff
kiriloff

Reputation: 26333

This is using setattr that you tried to use in the first place

>>> l = [1,2,3]
>>> lst = Foo(l)
>>> setattr(lst, 'foo', 'bar')
>>> lst.foo
'bar'

Upvotes: 0

Eric
Eric

Reputation: 97571

>>> class Foo(list): pass
>>> l = Foo([1,2,3])
>>> l.foo = 'bar'
>>> l
[1, 2, 3]

Upvotes: 4

Related Questions