Timothy Baldridge
Timothy Baldridge

Reputation: 10663

Make a function live "inside" a module

I'm building a function at run-time with byteplay.py. When I'm done with constructing the bytecodes, I take the code object and create a new function like this:

module = new.module("foomodule")
fn = new.function(c.to_code(), {}, name.name)
setattr(module, "fn", fn)

Now this would appear to work, I can call module.foo() and it works as expected. However, if fn tries to call a global function, the call fails, since my list of globals passed into new.function is empty {}.

The issue is, I want the list of globals to always refer to module. So how do I do this? How do I pass a module into new.function?

Upvotes: 1

Views: 99

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69051

Change your second line to:

fn = new.function(c.to_code(), module.__dict__, name.name)

Upvotes: 2

Related Questions