2

Hello everyone is there a better way to dynamically create/call variables, I'm trying to create a structural parser that will read the object data in a block and create those objects as variables dynamically as they are discovered.

This is and example of my current method, but it feels like I'm going about this wrong.

>>> VAR="VAR2"
>>> class item():
...     pass
... 
>>> newitem=item()
>>> exec('newitem.'+VAR+'=\''+'hello'+'\'')
>>> newitem.VAR2
'hello'
>>> 

2 Answers 2

4

Use setattr.

setattr(object, attribute_name, value)

So, for example, setattr(a, "pancakes", "syrup") is (more or less) the same as a.pancakes = "syrup"

So, you can use setattr(newitem, VAR, "hello") to make newitem.VAR2 become "hello".

Sign up to request clarification or add additional context in comments.

Comments

4

I think you're on the right track for dynamically creating variables, although I would question why you're not using a hashmap. Why not do

newitem = {}
newitem[VAR] = 'hello'

Try to stay away from the eval statement as much as possible because you have to adjust for "python injection". i.e. VAR could include a "'" which might cause invalid code. It's much easier to just use regular Python constructs when possible

1 Comment

yeah this is probably the more saner way of doing things, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.