Technique for safely reloading dynamically generated module

Chris Angelico rosuav at gmail.com
Thu Jul 21 12:16:39 EDT 2016


On Fri, Jul 22, 2016 at 2:07 AM, Malcolm Greene <python at bdurham.com> wrote:
> The source file we're generating has one main function (go) with some
> supporting functions and classes as well. Will there be any problems
> referencing additional functions or classes defined in the source that
> gets passed to exec ... as long as references to those functions and
> classes happen within the generated module?
>
> I assume that one downside to the exec() approach is that there is no
> persistent namespace for this code's functions and classes, eg. after
> the exec() completes, its namespace disappears and is not available to
> code that follows?

Functions keep references to their globals, so you should be safe.

> The Python documentation also warns: "Be aware that the return and yield
> statements may not be used outside of function definitions even within
> the context of code passed to the exec() function. The return value is
> None."

Yeah, that's just emphasizing that exec() is looking for module-level
code. Just as you can't put a flush-left "return" statement into a .py
file, you can't use one in exec(). As long as your code builder is
returning a string equivalent to what you'd find in an actual Python
module (that is, exactly what it's already doing, given that you
currently attempt to import it), you'll be fine.

ChrisA



More information about the Python-list mailing list