python - How to use invalid variable names in exec or eval? -


i want calculate formula variables in dictionary. example:

d = {'a': 1} exec('b=a+1', globals(), d) # d => { 'a': 1, 'b': 2 } 

since data source of dictionary outside of python (e.g., json / yaml ), key name of dictionary can invalid variable name of python. following code:

d = {':a': 1} exec('b=:a+1', globals(), d) # expected d => { ':a': 1, 'b': 2} 

throws error:

file "<string>", line 1 b=:a   ^ syntaxerror: invalid syntax 

do have idea use invalid variable in exec or eval?

[replace based approach]

how this? confirmed works correctly.

but can not handle new invalid variable allocation ":b = :a + 1".

d = {':a': 1} expression = 'b=:a+1'  def exec2(expression, d):      d2 = {}     keymap={}     idx, (k, v) in enumerate(d.items()):         k2 = "_" + str(idx)         d2[k2] = v         keymap[k2] = k          expression = expression.replace(k, k2)      # d2 => {'_0': 1}     # expression => b=_0+1      exec(expression, globals(), d2)      k2, v in d2.items():         if k2 in keymap:             k = keymap[k2]             d[k] = v         else:             d[k2] = v     # d => {':a': 1, 'b': 2}     return d 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -