Python Forum

Full Version: common code, def a function vs exec() a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
If you make an example, I could better understand what your issue is.
documentation of the exec() builtin function describes passing it either a string (i've done that before) or a code object. what is a code object and how do i make one?

the short explanation is the i need to run some code that is written once and do that run of it in two places. this code also needs to run in the same context (sees all the same namespace. normal functions don't do this; they create a new context. so i need a way to run that block of code from 2 different places while keeping it in the same context.

i tried it; it doesn't work. a break done inside exec() where the exec() is in a loop does not exit that loop. the error message said break was done not in a loop,
OK, I understand
i do use exec() to process config files. that lets me put dynamic code in the config file from simple things like:
howmanytimes = 2**32
to more complex code that figures out config parameters based on other information sources. it gets the local namespace back from exec() and deletes key '__builtins__' from that dictionary. it then hangs on to that dictionary for config settings or sets up things, sooner, such as opening files.
OH, that sounds complicated.
it's rather simple. you know where the file is. read the whole thing into a string. create an empty dictionary. call exec() passing the string and empty dictionary. del thatdict['__builtins__'] (exec() added it). now you have a dictionary of what variables that config file assigned as locals.
Ok, I will try tommorrow.