Search code examples
cython

Cython and Exec()?


If I made a python file named hello.py that has a script made like this.

msg = input("insert your message here: ")
script = '''
def say_something():
    print("{msg}")
'''

exec(script)
say_something()

And then I tried to use Cython

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("Hello.py")
)

It will show an error like this: undeclared name not builtin: say_something

I do understand why this happens but I'm not really an expert with python and C just yet. This is just an example, but it's similar to what I'm trying to do with one of my projects. Is there any way I could resolve this? I want to find a way to convert the script string into C as well.

I was trying to build an editable python script.


Solution

  • Cython compiles the Python functions to a native binary that does what the CPython interpreter should do. exec is a function that execute arbitrary code at runtime (which is generally a very bad idea for speed, maintainability/readability and security). Cython does not support exec because it would mean that the could would be compiled at runtime. Thus, the code executed by exec cannot be a Cython code. However, the exec function can still be used to execute a pure-Python code. The error can be removed by turning off the Cython.Compiler.Options.error_on_unknown_names in the setup script (just before calling setup) as pointed out by @DavidW. With this Cython will not complain when it does not find a function defined by exec (or similar methods). Please keep in mind that CPython can only be used in this case instead of Cython (which partially defeat the purpose of using Cython in the first place).