3

Realize this is a rather obscure question, so I'll explain why I'm looking into this.

A Python jit compiler takes a callable and returns a callable.

This is fine, however - the API I'm currently working with uses a Python code object.

A simplistic answer to this question would be to write a function to execute the code, eg:

def code_to_function(code):
    def fn():
        return eval(code)
    return fn

# example use
code  = compile("1 + 1", '<string>', 'eval')
fn = code_to_function(code)
print(fn())  # --> 2

Which is correct, but in this case the jit (happens to be numba), won't evaluate the actual number crunching parts - which is needed to be useful.

So the question is, how to take a code object which evaluates to a value, and convert/construct a callable from it?


Update, thanks to @jsbueno's answer, here's an example of a simple expression evaluator using numba.

2 Answers 2

4
from types import FunctionType

new_function = FunctionType(code,  globals[, name[, argdefs[, closure]]])

The remaining parameters above may be taken from the original function you have.

Sign up to request clarification or add additional context in comments.

Comments

0

Edit, @jsbueno answer is better, but this may be a useful alternative, or at least be interesting for Python developers interested in manipulating functions.


This can be done by replacing a functions __code__, attrubute, eg:

def code_to_function(code):
    def fn_dummy():
        return None

    fn_dummy.__code__ = code
    return fn_dummy


# example use
code  = compile("1 + 1", '<string>', 'eval')
fn = code_to_function(code)
print(fn())  # --> 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.