Welcome, guest | Sign In | My Account | Store | Cart

Python Attribute List

Add/set attributes to python lists.

A google search for "add attributes to python lists" yields no good stackoverflow answer, hence the need for this.

Useful for machine learning stuff where you need labeled feature vectors.

This technique can be easily adapted for other built-ins (e.g. int).

The Problem
a = [1, 2, 4, 8]
a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x'
The Solution
a = L(1, 2, 4, 8)
a.x = "Hey!"
print a       # [1, 2, 4, 8]
print a.x     # "Hey!"
print len(a)  # 4

# You can also do these:
a = L( 1, 2, 4, 8 , x="Hey!" )                 # [1, 2, 4, 8]
a = L( 1, 2, 4, 8 )( x="Hey!" )                # [1, 2, 4, 8]
a = L( [1, 2, 4, 8] , x="Hey!" )               # [1, 2, 4, 8]
a = L( {1, 2, 4, 8} , x="Hey!" )               # [1, 2, 4, 8]
a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8]
a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ** b for b in range(4) )( x="Hey!" )  # [1, 2, 4, 8]
a = L( 2 )                                     # [2]
Python, 39 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class L(list):
    """
    A subclass of list that can accept additional attributes.
    Should be able to be used just like a regular list.

    The problem:
    a = [1, 2, 4, 8]
    a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x'

    The solution:
    a = L(1, 2, 4, 8)
    a.x = "Hey!"
    print a       # [1, 2, 4, 8]
    print a.x     # "Hey!"
    print len(a)  # 4

    You can also do these:
    a = L( 1, 2, 4, 8 , x="Hey!" )                 # [1, 2, 4, 8]
    a = L( 1, 2, 4, 8 )( x="Hey!" )                # [1, 2, 4, 8]
    a = L( [1, 2, 4, 8] , x="Hey!" )               # [1, 2, 4, 8]
    a = L( {1, 2, 4, 8} , x="Hey!" )               # [1, 2, 4, 8]
    a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8]
    a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8]
    a = L( 2 ** b for b in range(4) )( x="Hey!" )  # [1, 2, 4, 8]
    a = L( 2 )                                     # [2]
    """
    def __new__(self, *args, **kwargs):
        return super(L, self).__new__(self, args, kwargs)

    def __init__(self, *args, **kwargs):
        if len(args) == 1 and hasattr(args[0], '__iter__'):
            list.__init__(self, args[0])
        else:
            list.__init__(self, args)
        self.__dict__.update(kwargs)

    def __call__(self, **kwargs):
        self.__dict__.update(kwargs)
        return self
Created by webby1111 on Tue, 29 Sep 2015 (MIT)
Python recipes (4591)
webby1111's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks