vendredi 7 février 2020

Is this use of exec pythonic?

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!

Aucun commentaire:

Enregistrer un commentaire