2

I am currently reading lines from a .csv file and storing the data in a list of array.array('f') objects. Since I will be passing the individual lines to different processes I would like to store an (line) id with every array.array object.

I know I can do this obviously by defining a new class and encapsulating the data, but I was wondering if there is a different way by adding dynamically a custom attribute to array.array. The benefit would be not having an additional look up when accessing the data itself and not having to define a class with just the id and the data.

I know a list of tuples are an option too, but in the near future I will want to store mutable attributes.

What is the python way to do this?

2
  • 2
    array.array objects don't allow for arbitrary attributes, no. Encapsulation is your only option there. Commented May 22, 2015 at 16:23
  • Delegation is your friend. Commented May 22, 2015 at 16:41

2 Answers 2

2

One option would be to store each line in a Dict that included additional metadata. This is analogous to using Decorator pattern to add metadata field(s) to your type.

For example, suppose you had a test file like so:

$ cat test.file 
line_1
line_2

You could do something like the following to add metadata:

>>> with open('./test.file','rb') as fin:
...   for line in fin:
...     linecount += 1
...     d = {'line':line,'metadata':'a line %d' % linecount}
...     lines.append(d)
... 
>>> print(lines)
[{'line': 'line_1\n', 'metadata': 'a line 1'}, {'line': 'line_2\n', 'metadata': 'a line 2'}]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is similar as laike9m suggestion. I guess this is the solution if I don't want to add a new class. Thanks.
1

You should define a MyArray class and delegates everything to array.array. So what do you think of this even simpler solution?

id = "your_id"
array = array.array('f', [...])
data = {id: array}

3 Comments

I am not refusing to define a new class, I was merely asking if there was a dynamic way to add attributes to an existing class. Your suggestion is an option though.
In general, you can add new attr to an existing class/instance, but not array.array. If you modify the built-in objects like array, it may not behave what it should be then do you harm, so Python prevent people from doing this.
Yes this is what I noticed when I tried adding a new function to the class. I guess it makes sense. I will wait a bit for other suggestions and benchmark the impact but I will probably go for this solution. Not exactly what I wanted but it seems to be the only way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.