Reputation: 4133
I'm trying to associate additional data with a Python list. Ideally, I'd like to add custom attributes to a list object, similar to how you'd add attributes to a custom class. For example:
a = [1, 2, 4, 8]
a.x = "Hey!" # I'd like this to work without errors
However, when I attempt this, I get the following error:
AttributeError: 'list' object has no attribute 'x'
I understand that Python lists don't support adding arbitrary attributes out of the box. I also tried using setattr
, but it gave me a similar error:
setattr(a, "k", 98) # Raises AttributeError
I cannot create a custom class DummyList(list)
to work around this (for reasons). I also don't want to use some global variable that holds the attributes for the lists. Are there any workarounds to achieve this in Python?
Upvotes: 0
Views: 135