Is this use of exec pythonic? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Is this use of exec pythonic? (/thread-24279.html) |
Is this use of exec pythonic? - psolar - Feb-07-2020 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 = msgThank you all in advance for your thoughts! RE: Is this use of exec pythonic? - buran - Feb-07-2020 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
|