marshal
marshal

Reputation: 19

Dynamically creating a class

I have a function which returns me two lists, symbols and data where the corresponding values are with the same index. For example symbols[i] gives the variable name and data[i] gives the actual value (int).

I would like to use these two lists to dynamically create a class with static values of the following format:

class a:

    symbols[i] = data[i]
    symbols[i+1] = data[i+1]

and so on so that I could later refer to the values like this:

a.symbols[i]
a.symbols[i+1] 

where symbols[i] and symbols[i+1] should be replaced with the wanted variable name, like a.var1 or a.var2

How could this be achieved?

Edit: added detail below

So I have a main program lets say def main() which should read in a list.dat of this style:

dimension1;0.1
dimension2;0.03
dimension3;0.15

and separate the values to symbols and data lists.

So I don't know how many values there are exactly in these lists. I want to create a class dynamically to be able to refer to the values in the main program and to give the class to sub functions as an argument like def sub1(NewClass, argument1, argument2) etc. At the moment I am using a manually created simple python list (list.py) of the following format:

dimension1 = 0.1
dimension2 = 0.03
dimension3 = 0.15

and then using from list import * in the main program and also in the sub functions, which causes a SyntaxWarning telling me that import * only allowed at module level. So what I actually want is a smart and consistent way of handling the parameters list and transferring it to another functions

Upvotes: 1

Views: 84

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122154

I suspect what you actually want, re-reading the description, is to use type as follows:

NewClass = type('NewClass', (object,), dict(zip(symbols, data)))

Given a minimal example:

>>> symbols = 'foo bar baz'.split()
>>> data = range(3)

The outcome would be:

>>> NewClass.foo
0
>>> NewClass.bar
1
>>> NewClass.baz
2

Using zip allows you to easily create a dictionary from a list of keys and a list of associated values, which you can use as the __dict__ for your new class.

However, it's not clear why you want this to be a class, specifically.

Upvotes: 1

Nhor
Nhor

Reputation: 3940

You can create a class dynamically with type. If I understand what you want to achieve here, your code will look like:

my_classes = []
for i in range(0, len(data), 2):
    my_classes.append(
        type('A%d' % i, (), {'var1': data[i], 'var2': data[i+1]})
    )

Upvotes: 1

Related Questions