Python Forum

Full Version: Is this use of exec pythonic?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

Consider this code:

self._t10_test = None
self._t20_test = None
self._t30_test = None

id_lst = ['10', '20', '30']
msg_lst = ['Message for A', 'Message for B', 'Message for C')
It would be correct to make this use of exec?

for id, msg in zip(id_lst, msg_lst):
    exec((f'self._t{id}_test = {msg}')
Or would be more pythonic this?
for id, msg in zip(id_lst, msg_lst):
    set_msg(id, msg)


def set_msg(id, msg):
    if id == '10':
        self._t10_test = msg
    elif id == '20':
        self._t20_test = msg
    elif id == '30':
        self._t30_test = msg
  
Thank you all in advance for your thoughts!
can you elaborate what you want to achieve, because this looks very much like XYproblem. I guess you try to create a name dynamically and that is really bad idea. But the exec snippet is even worse