relima
relima

Reputation: 3423

Is it possible to generate variables from a list?

Is it possible to generate variables on the fly from a list?

In my program I am using the following instruction:

for i in re.findall(r"...(?=-)", str(vr_ctrs.getNodeNames())):
    tmp_obj = vr_ctrs.getChild(i+"-GEODE")

    TMP.append([tmp_obj.getPosition(viz.ABS_GLOBAL)[0],
                tmp_obj.getPosition(viz.ABS_GLOBAL)[1], 
                tmp_obj.getPosition(viz.ABS_GLOBAL)[2]])

which builds me a list on TMP. Would be possible to generate a new variable for each one of the elements that I am appending to TMP?

Thanks

Upvotes: 0

Views: 169

Answers (2)

PaulMcG
PaulMcG

Reputation: 63749

I would suggest that instead of creating variables, that you capture these entries in a dict, using what you would have used as the variable name for the dict keys. Then you can easily navigate through the parsed data by accessing dict.keys(), and you wont have to sort out your variables from other local or global variables. Also, if you happen to parse something that accidentally collides with a Python keyword (like 'for', for example), then using that as a dict key will still work, while using it as a variable or attribute name is not going to work.

Upvotes: 4

dkagedal
dkagedal

Reputation: 578

The global variables are in a dictionary that you can get by calling the globals() function.

globals()["foo"] = 17
foo  # => 17

But you should probably refactor your code to use objects, and then use setattr() instead.

Upvotes: 1

Related Questions