What does Cython do with imports?

2020-08-26 04:03发布

问题:

I want to create a Python extension and I really like the idea of using Cython. Mainly to gain more knowledge about it and to take advantage of speed gains, if any. I have read quite a bit of Cython documentation but I am not a computer scientist (yet) and do not have an in depth knowledge to understand the low-level basics, hence the reason for my following questions:

I was just wondering, what happens if I use an externally imported (for example, an ORM or SQL library or any other 3rd party library) into the Python extension I am developing?

How does Cython handle it?

Is there a difference if this imported library/extension is in pure Python or if it's also compiled?

What is the right way to handle this?

Thank you.

PS. Questions are typed in bold.

回答1:

The goal of cython is to be compatible with python, i.e. that you can cythonize any python code and it will work as before. Currently, a large fraction of python code already works. Cython furthermore allows you to optimize parts of your code and compile it into more efficient C code.

That being said any python import will stay as they were by default. Any calls to them will be issued as python commands. Even if the module is written in C, cython will take the detour via python to call functions of the module. If you want to use a C library directly, you have to have cython bindings for them. The cython documentation explains how to do this.

Generally, python acts as an overseer and handles the scopes of modules/classes. If code in one module calls any python function (or accesses a python variable), python will resolve the call according to the scope of the caller. If the called function happens to be in a second module, python is happily using it. The caller will just get the result and should not really care whether the other function was in a different module or not. The key is thus the scoping rules of python that decide which function is called.