Python Forum
Is this use of exec pythonic?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is this use of exec pythonic?
#1
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!
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pythonic from a C++ perspective PyDan 2 1,514 Sep-18-2023, 11:39 AM
Last Post: PyDan
  How to avoid exec(), globals(), locals(), eval() paul18fr 10 8,043 Apr-21-2021, 05:53 PM
Last Post: snippsat
  exec in a function paul18fr 6 4,771 Apr-19-2021, 11:10 AM
Last Post: paul18fr
  exec + subprocess = UnboundLocalError paul18fr 6 4,999 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  exec() in class, NameError niski1996 6 5,916 Apr-20-2020, 07:14 PM
Last Post: niski1996
  which is "better" (or more Pythonic)? Skaperen 2 2,905 Feb-01-2020, 03:10 PM
Last Post: Skaperen
  which is "better" (or more Pythonic)? Skaperen 7 4,640 Feb-01-2020, 03:51 AM
Last Post: Skaperen
  problem using exec to save local variables dkarl 0 2,552 Dec-01-2019, 08:52 AM
Last Post: dkarl
  which is "better" (or more Pythonic)? Skaperen 8 5,018 Nov-16-2019, 06:46 PM
Last Post: Skaperen
  which is more Pythonic? Skaperen 5 4,082 Jul-16-2019, 01:00 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020