Python Forum
common code, def a function vs exec() a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
common code, def a function vs exec() a string
#1
in a long loop i have a big series of tests, some being multi-level nested if statements that do breaks to break out of that long loop. they are located in the upper part of the loop right after a cloud API operation. i need to duplicate these exact same tests in the lower part of the loop after another slightly different cloud API operation. i can't really put these in a "do twice" loop because of the diversity of surrounding code. so i was thinking of putting them in a function so i have just one copy of that code, but this means passing a long bunch of variables to the function.

i wish there was a way to run some common section of code in the same local context so that it has access to the same local (and global) variable space. it would be nice to have a way, in a function, to make its local (and global) variable space be that of one or two dictionaries passed to the function for such purpose.

can i just put all that code in a triple-quoted literal and use exec() on it, twice?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
common code, def a function vs exec() a string - by Skaperen - May-24-2019, 08:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python code for Longest Common Subsequence Bolt 3 1,076 Sep-22-2023, 08:09 AM
Last Post: Bolt
  Changing a string value to a numerical value using python code and a lamda function Led_Zeppelin 6 1,909 Jul-05-2022, 11:29 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 2,733 May-13-2022, 07:28 PM
Last Post: mikepy
  a function common to methods of a class Skaperen 7 2,818 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  How to avoid exec(), globals(), locals(), eval() paul18fr 10 5,383 Apr-21-2021, 05:53 PM
Last Post: snippsat
  exec in a function paul18fr 6 3,609 Apr-19-2021, 11:10 AM
Last Post: paul18fr
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 2,094 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  exec + subprocess = UnboundLocalError paul18fr 6 3,701 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  exec() in class, NameError niski1996 6 4,184 Apr-20-2020, 07:14 PM
Last Post: niski1996
  Is this use of exec pythonic? psolar 1 1,908 Feb-07-2020, 12:23 PM
Last Post: buran

Forum Jump:

User Panel Messages

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