Sebastian Alvarez
Sebastian Alvarez

Reputation: 97

Customize compile function in python?

RestrictedPython module has a restricted compiler in which you can compile code and customize some python features. For example, you can replace the builtin print function.

That's what I need to do. I need to compile some code but defining my own print function. I can't use this restricted compiler because it has a lot of restrictions I don't need at now.

Do you know any other compiler in which I can define my own print function?

Upvotes: 0

Views: 307

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122252

Just use regular Python then; in Python 2 use:

from __future__ import print_function

or use Python 3, and print() is then a function. You can redefine that function:

from __future__ import print_function
try:
    # Python 2
    from __builtin__ import print as builtin_print
except ImportError:
    from builtins import print as builtin_print

def print(*args, **kw):
    # do something extra with *args or **kw, etc.
    builtin_print(*args, **kw)

Like any other built-in function you can define your own function using the same name. In the above example I used the __builtin__ / builtins module to access the original.

If you are using exec(), you can pass in the print() function you defined as an extra name in the namespace you pass in:

exec(code_to_execute, {'print': your_print_function})

For Python 2, you do need to compile the code first to switch off the print statement and enable the print() function; use the compile() function to produce a code object to pass to the exec statement:

import __future__

code_to_execute = compile(
    code_to_execute_in_string, '', 'exec',
    flags=__future__.print_function.compiler_flag)

I used the __future__ module to obtain the right compiler flag.

Upvotes: 2

Related Questions