5

I have a python class, and I need to add an arbitrary number of arbitrarily long lists to it. The names of the lists I need to add are also arbitrary. For example, in PHP, I would do this:

class MyClass {

}

$c = new MyClass();
$n = "hello"
$c.$n = array(1, 2, 3);

How do I do this in Python?

I'm also wondering if this is a reasonable thing to do. The alternative would be to create a dict of lists in the class, but since the number and size of the lists is arbitrary, I was worried there might be a performance hit from this.

If you are wondering what I'm trying to accomplish, I'm writing a super-lightweight script interpreter. The interpreter walks through a human-written list and creates some kind of byte-code. The byte-code of each function will be stored as a list named after the function in an "app" class. I'm curious to hear any other suggestions on how to do this as well.

2 Answers 2

5

Use setattr.

>>> class A(object):
...     pass
... 
>>> a = A()
>>> f = 'field'
>>> setattr(a, f, 42)
>>> a.field
42
Sign up to request clarification or add additional context in comments.

Comments

1

I would write it the simplest way for now, and profile next, and then look to optimize specific elements.

Let's remember the KISS principle.

2 Comments

lol, sure, but I just wanted to clarify, it sounds like you're still in the dreaming stage, so I would wait till you've got a working prototype because this sounds like a specific optimization. The dict list is fine.
I have some mock classes and I'm gradually filling them out. I was at the stage where I was figuring out how to hold the compiled data of a script. But really, so far I've done far more thinking and dreaming than code, because there's threads involved and I'm trying not to blow my foot off :)

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.