Reputation: 23
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'
>>>
Upvotes: 2
Views: 4256
Reputation: 8951
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
Upvotes: 4
Reputation: 9666
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".
Upvotes: 4