How to set custom locals for function call?

Chris Angelico rosuav at gmail.com
Tue Sep 1 21:48:02 EDT 2020


On Wed, Sep 2, 2020 at 11:29 AM Andras Tantos
<python-list at andras.tantosonline.com> wrote:
> OK, and sorry about that. May third time a charm?

Thank you! Whatever you did this time, that worked :)

> Indeed, I'm executing a code object and not a string. Is there any way
> to get to the string version of the function and force a re-compile of
> it during an exec? Would it help?

Eeeuuuuhhhhhhhh.... normally you'd do that by, well, *not* compiling
it. But maybe the inspect module can help here:

https://docs.python.org/3/library/inspect.html#inspect.getsource

There's no guarantee that it will work though.

> I guess if I was doing that, I would need to execute the 'body' of the
> function within the exec and by passing in a local parameter I can
> pretend it has its own call-stack entry. But is that truly equivalent to
> calling the original function?

I think it is getting an actual call stack entry anyway.

Now, if your goal is to do something with an expression evaluator,
then there are LOTS of options. Let's say you want to allow people to
write code that implicitly calls on some data source, so typing "x **
2 + y ** 2" would look up x and y in some way and then do arithmetic
with them. If you get the original source as a string, you can most
certainly do things with the globals as you compile it. Or if you want
more reliability, compile it to AST, walk the tree, and replace nodes
as required, before compiling it the rest of the way for execution. Or
run the code at global scope, with the globals doing your magic and
the builtins doing everything else. Lots of ways to do things, as long
as you start with the source code.

ChrisA


More information about the Python-list mailing list