__kwdefaults__special attribute of fused functions. (Github issue #1470)
prange()loops appear inside of with-statements. (Github issue #2780)
ZeroDivisionError. (Github issue #2820)
libc.signalwas corrected. (Github issue #2756)
try-statements generated invalid C code. (Github issue #2274)
warn.undeclareddirective, Cython’s own code generated warnings that are now fixed. Patch by Nicolas Pauss. (Github issue #2685)
PyBUF_NDflag to be set. Patch by John Kirkham. (Github issue #2716)
operatorcould fail to compile. (Github issue #2671)
from ... cimport ...constructs were not correctly considered when searching modified dependencies in
cythonize()to decide whether to recompile a module. Patch by Kryštof Pilnáček. (Github issue #2638)
cpython.arraydeclarations was corrected. Patch by John Kirkham. (Github issue #2712)
mypycompatible PEP-484 declarations were added for Cython’s C data types to integrate with static analysers in typed Python code. They are available 在
Cython/Shadow.pyimodule and describe the types in the special
cythonmodule that can be used for typing in Python code. Original patch by Julian Gethmann. (Github issue #1965)
@cython.nogilis supported as a C-function decorator in Python code. (Github issue #2557)
cython.inline()supports a direct
language_levelkeyword argument that was previously only available via a directive.
3strwas added that mostly corresponds to language level 3, but keeps unprefixed string literals as type ‘str’ in both Py2 and Py3, and the builtin ‘str’ type unchanged. This will become the default in the next Cython release and is meant to help user code a) transition more easily to this new default and b) migrate to Python 3 source code semantics without making support for Python 2.x difficult.
.cxx. (Github issue #2266)
cythonizecommand accepts compile time variable values (as set by
DEF) through the new
-E选项。 Patch by Jerome Kieffer. (Github issue #2315)
pyximportcan import from namespace packages. Patch by Prakhar Goel. (Github issue #2294)
pylifecycleC-API functions were added in a new .pxd file
%ais included in the string formatting types that are optimised into f-strings. In this case, it is also automatically mapped to
%rin Python 2.x.
CYTHON_HEX_VERSIONto access Cython’s version in the same style as
libc.mathare now declared as
constto simplify their handling.
check_sizeclause was added to the
ctypedef classname specification to allow suppressing warnings when importing modules with backwards-compatible
PyTypeObjectsize changes. Patch by Matti Picus. (Github issue #2627)
__rmod__()method if the right side is a string subclass that implements it. (Python issue 28598)
language_level=3did not apply to the first token in the source file. (Github issue #2230)
@cfunc函数。 (Github issue #459)
consttypes were not excluded from star-import assignments which could lead to invalid C code. (Github issue #2621)
get_array_base()were adapted to the current numpy C-API recommendations. Patch by Matti Picus. (Github issue #2528)
c_string_encodingdirective appeared within the first two lines. (Github issue #2632)
language_level(2, 3 or ‘3str’) is set explicitly, neither as a
cythonize()option nor as a compiler directive. This is meant to prepare the transition of the default language level from currently Py2 to Py3, since that is what most new users will expect these days. The future default will, however, not enforce unicode literals, because this has proven a major obstacle in the support for both Python 2.x and 3.x. The next major release is intended to make this change, so that it will parse all code that does not request a specific language level as Python 3 code, but with
strliterals. The language level 2 will continue to be supported for an indefinite time.
optimize("Os")was replaced by the similar attribute
coldto reduce the code impact of the module init functions. (Github issue #2494)
tp_clear()in a subtype of an
@no_gc_clearextension type generated an invalid C function call to the (non-existent) base type implementation. (Github issue #2309)
UnicodeEncodeErrorin Py2 when
%sformatting is optimised for unicode strings. (Github issue #2276)
abs()is faster for Python long objects.
end()were added to the declaration of
libcpp.string. Patch by Alex Huszagh. (Github issue #2123)
bucket_count()are declared for
libcpp.unordered_map. Patch by Valentin Valls. (Github issue #2168)
switchstatement generation failed to apply recursively to the body of converted if-statements.
NULLwas sometimes rejected as exception return value when the returned type is a fused pointer type. Patch by Callie LeFave. (Github issue #2177)
PyFrozenSet_New()was accidentally used in PyPy where it is missing from the C-API.
ctypedef. (Github issue #2148)
nogil. (Github issue #2157)
basestring(bytes or unicode) as result type in some cases where
byteswould have been safe to infer. (Github issue #2153)
Nonewas accidentally disallowed as typed return value of
dict.pop(). (Github issue #2152)
object，和 the other bases must not be cdef classes.)
constmodifier can be applied to memoryview declarations to allow read-only buffers as input. (Github issues #1605, #1869)
cdef externblock is copied verbatimly into the generated file. Patch by Jeroen Demeyer. (Github issue #1915)
@cython.iterable_coroutinechanges its type at compile time to make it iterable. While this is not strictly in line with PEP-492, it improves the interoperability with old-style coroutines that use
Py_tss_ttype defined in PEP-539 and automatically initialises variables declared with that type to
Py_tss_NEEDS_INIT, a value which cannot be used outside of static assignments.
.discard()are optimised. Patch by Antoine Pitrou. (Github issue #2042)
dict.pop()is optimised. Original patch by Antoine Pitrou. (Github issue #2047)
alist.extend([a,b,c])is optimised into sequential
list.append()calls for short literal sequences.
bytearrayoperations have been optimised similar to
view[i][j]is now optimised into
cython.*types can now be mixed with type declarations in Cython syntax.
libc/signal.pxd. Patch by Jeroen Demeyer. (Github issue #1914)
CYTHON_NO_PYINIT_EXPORTwill prevent the module init function from being exported as symbol, e.g. when linking modules statically in an embedding setup. Patch by AraHaan. (Github issue #1944)
Extension()that is compiled via
cythonize(), it was previously ignored and replaced by the source file name. It can now be used to override the target module name, e.g. for compiling prefixed accelerator modules from Python files. (Github issue #2038)
num_threadsparameter of parallel sections were not sufficiently validated and could lead to invalid C code. (Github issue #1957)
__richcmp__()method was corrected to recognise the type of the first argument as
self. It was previously treated as plain object, but CPython actually guarantees that it always has the correct type. Note: this can change the semantics of user code that previously relied on
unordered_mapwere corrected. Patch by Michael Schatzow. (Github issue #1484)
vectorwere corrected. Patch by Alex Huszagh. (Github issue #1870)
stringdeclarations were corrected, together with the coercion behaviour of string literals into C++ strings. (Github issue #2132)
libc.limitswere corrected. Patch by Jeroen Demeyer. (Github issue #2016)
@cython.finalwas not accepted on Python classes with an
@cython.cclassdecorator. (Github issue #2040)
PyInstanceMethodwrappers for methods in Python 3. Patch by Jeroen Demeyer. (Github issue #2105)
bytearraytype could not be used as base type of cdef classes. (Github issue #2106)
@cython.locals(x="ExtType")failed to find the named type. (Github issue #1962)
PyThreadStatein CPython 3.7.
PyWeakref_GetObject()API declaration. Patch by Jeroen Demeyer (Github issue #1975).
__lt__etc. in extension types did not type their first argument as the type of the class but
object. (Github issue #1935)
std::unordered_map.erase()was declared with an incorrect
voidreturn type in
libcpp.unordered_map. (Github issue #1484)
fallthroughattribute before C++11 and similar issue in clang. (Github issue #1930)
--verbosethat shows details about the distutils invocation. Patch by Boris Filippov (Github issue #1881).
__path__correctly available to module level code and improves the support for module-level relative imports. (Github issues #1715, #1753, #1035)
cython.int) are evaluated as C type declarations and everything else as Python types. This can be disabled with the directive
annotation_typing=False. Note that most complex PEP-484 style annotations are currently ignored. This will change in future releases. (Github issue #1850)
__lt__etc. for comparisons instead of the low-level
__richcmp__method. (Github issue #690)
@cython.exceptval(x=None, check=False)that makes the signature declarations
except *available to pure Python code. Original patch by Antonio Cuni. (Github issue #1653)
embedsignaturedirective. Patch by Lisandro Dalcin (Github issue #1781).
libpython.py) was updated to the latest version in CPython 3.7 (git rev 5fe59f8).
except *if the returned type allows it. Note that this feature is subject to safety limitations, so it is still better to provide an explicit declaration.
%%cython --pgofor profile guided optimisation. It compiles the cell with PGO settings for the C compiler, executes it to generate a runtime profile, and then compiles it again using that profile for C compiler optimisation. Currently only tested with gcc.
len(memoryview)can be used in nogil sections to get the size of the first dimension of a memory view (
shape). (Github issue #1733)
range(enum)were not converted into C for-loops. Note that it is still recommended to use an explicit cast to a C integer type in this case.
DEFassignments were evaluated even when they occur inside of falsy
IFblocks. (Github issue #1796)
frame.f_localsof a Cython function (e.g. from a debugger or profiler could modify the module globals. (Github issue #1836)
fr'...') were resolved instead of passing them through as expected.
cython.int) and Python builtin types are currently considered as type declarations. Everything else is ignored, but this will change in a future Cython release. (Github issue #1672)
Trueby default, which enables parsing type declarations from annotations.
.pxdoverride for their
__releasebuffer__slot (e.g. as provided by Cython for the Python
array.arraytype) could leak a reference to the buffer owner on release, thus not freeing the memory. (Github issue #1638)
constinteger variables could generate invalid code. (Github issue #1798)
PickleErrorgenerated invalid unpickling code. Patch by Jason Madden (Github issue #1786).
.pyfiles. Patch by Guro Bokum (Github issue #1784).
__all__variable and ignores names with leading-underscore (like
import *does). Patch by Syrtis Major (Github issue #1625).
abs()is optimised for C complex numbers. Patch by da-woods (Github issue #1648).
import cython_runtime; cython_runtime.cline_in_traceback=True. The default has been changed to False.
Py_UNICODEused the integer value instead of the Unicode string value. Code that relied on the previous behaviour now triggers a warning that can be disabled by applying an explicit cast. (Github issue #1602)
iter*methods failed in PyPy3. Patch by Armin Rigo (Github issue #1631).
unraisable_tracebacksoption now defaults to
isinstance(o, Exception)(Github issue #1496).
cython.view.arraymissing utility code in some cases (Github issue #1502).
Cython.Distutils.build_exthas been reverted, temporarily, to be
old_build_extto give projects time to migrate. The new build_ext is available as
cdef dict __dict__is declared in the class. Patch by empyrical.
cython.no_gcto fully disable GC for a cdef class. Patch by Claudio Freire.
locals(). Patch by da-woods.
pias alias constants to simplify usage as a drop-in replacement for Python’s math module.
numpy.pxdwere incorrect. Patch by Michael Seifert.
Cython.Distutils.build_exthas now been updated to use cythonize which properly handles dependencies. The old extension can still be found in
Cython.Distutils.old_build_extand is now deprecated.
directive_defaultsis no longer available in
__aiter__()method of asynchronous iterators to be a simple
defmethod instead of an
std::complexvalues failed to auto-convert from and to Python complex 对象。
distutilscompiler option do not require values anymore. Patch by Ian Henriksen.
longare now also available in compile time
DEFexpressions when compiling with Py3.
DEF) now behave in a more useful way by turning into Unicode strings when compiling under Python 3. This allows using them as intermediate values in expressions. Previously, they always evaluated to bytes objects.
numpy/math.pxdnow reflect the actual tristate
intreturn value instead of using
dict(...).items()failed to get optimised when dict arguments included keyword arguments.
any(genexpr)calls could warn about unused code. This fixes ticket 876.
生成器ABCs in the
backports_abcmodule if it can be imported. This fixes ticket 870.
posix.typeswas not declared as
operator!(). Patch by Leo Razoumov.
from xyz import *and global C struct/union/array variables could fail to compile due to missing helper functions. This fixes ticket 851.
cr_awaitto match CPython.
yieldin signature annotations and default argument values. Both are forbidden now.
nogilfunctions/sections and module init code.
CoroutineABCs in the
collections.abcstdlib module at import time to enable interoperability with code that needs to detect and process Python generators/coroutines. These ABCs were added in CPython 3.5 and are available for older Python versions through the
backports_abc模块 on PyPI. See https://bugs.python.org/issue24018
unicode.join()avoid the generator iteration overhead by inlining a part of their functionality into the for-loop.
typetype is now declared as PyTypeObject in source, allowing for extern functions taking type parameters to have the correct C signatures. Note that this might break code that uses
typejust for passing around Python types in typed variables. Removing the type declaration provides a backwards compatible fix.
boundscheck()are available as no-ops in pure Python mode.
NULLis allowed as default argument when embedding signatures. This fixes ticket 843.
--embed, the internal module name is changed to
__main__to allow arbitrary program names, including those that would be invalid for modules. Note that this prevents reuse of the generated C code as an importable module.
cpdef voidmethods are now permitted.
abs(cint)could fail to compile in MSVC and used sub-optimal code in C++. Patch by David Vierra, original patch by Michael Enßlin.
foo.pyx, the directories in
sys.pathare no longer searched when looking for
foo.pxd. Patch by Jeroen Demeyer.
Tools/) was extended and renamed to
jedityper.py(to make it importable) and now works with and requires Jedi 0.9. Patch by Tzer-jen Wei.
voidfailed to compile.
constC++ references in intermediate parts of longer expressions could fail to compile.
reversed(range())is optimised in the same way as
range(). Patch by Favian Contreras.
cythonize()is now an error to more easily detect accidental typos.
logaddexpfamily of functions in
numpy.mathnow has correct declarations.
_is no longer considered a cacheable builtin as it could interfere with gettext.
strgenerated incomplete code that failed to compile.
libcpp.castare now declared as
-ato generate the annotated HTML source view.
language='c++'into cythonize() globally enables C++ mode for all modules that were not passed as Extension objects (i.e. only source files and file patterns).
Py_hash_tis a known type (used in CPython for hash values).
PySlice_*()C-API functions are available from the
std::stringto Python byte strings failed when auto-decoding was enabled.
cythonize.pyscript was not installed on MS-Windows.
char*from a temporary Python string object is safer in more cases and can be done inside of non-trivial expressions, including arguments of a function call. A compile time error is raised only when such a pointer is assigned to a variable and would thus exceed the lifetime of the string itself.
__qualname__that provide the plain/qualified name of the generator function (following CPython 3.5). See http://bugs.python.org/issue21205
inlinefunction modifier is available as a decorator
@cython.inlinein pure mode.
use_switch(defaults to True) to optionally disable the optimization of chained if statement to C switch statements.
libcpp.castand C++ heap data structure operations in
posix.*were extended to cover more of the POSIX API. Patches by Lars Buitinck and Mark Peek.
slice()are translated to a straight C-API call.
char*from an indexed Python string generated unsafe reference counting code.
cdef func(floating[:] a, floating[:] b)). This is considered the expected behaviour by most users and was previously inconsistent with other structured types like C arrays. Code that really wants all type combinations can create the same fused memoryview type under different names and use those in the signature to make it clear which types are independent.
obj.pop(x)truncated large C integer values of x to
__init__.pycis recognised as marking a package directory (in addition to .py, .pyx and .pxd).
cython-mode.elfor Emacs no longer incorrectly highlights keywords found as part of longer names.
from cython.submodule cimport name.
dir()was not guaranteed to return a sorted list.
.append.__name__) could fail to compile.
c_string_encoding=asciifailed in Py3.3.
cython.arrayobjects was accidentally omitted in Py3.
isspace()could not be resolved by clang.
yieldis supported in
bytearrayhas become a known type and supports coercion from and to C strings. Indexing, slicing and decoding is optimised. Note that this may have an impact on existing code due to type inference.
cdef basestring stringvarand function arguments typed as
basestringis now meaningful and allows assigning exactly
unicodeobjects, but no subtypes of these types.
bin/cythonizeprovides a command line frontend to the cythonize() compilation function (including distutils build).
@cython.no_gc_clear阻止 objects from being cleared during cyclic garbage collection, thus making sure that object attributes are kept alive until deallocation.
__init__.pyfiles) now works, starting with Python 3.3.
unraisable_tracebacksdirective added to control printing of tracebacks of unraisable exceptions.
set.discard(a_tuple)failed with a TypeError in Py2.4.
__qualname__was incorrect for nested classes and inner classes/functions declared as
metaclasskeyword argument. In Py2 compilation mode, a
__metaclass__entry in the class dict will still take precedence if not using Py3 metaclass syntax, but only after creating the class dict (which may have been done by a metaclass of a base class, see PEP 3115). It is generally recommended to use the explicit Py3 syntax to define metaclasses for Python types at compile time.
__metaclass__class dict entry are ignored.
tp_finalize()for safer cleanup instead of
PyBuffer_FillInfo()and some missing bits in
typeused the wrong base type struct at the C level.
bintarguments now appear as type
wraparoundhandling. This helps with fixing invalid code that might fail in the face of future compiler optimisations.
isinstance(X, type)failed to get optimised into a call to
PyType_Check(), as done for other builtin types.
from datetime cimport *was removed from the “cpython” declaration package. This means that the “datetime” declarations (added in 0.19) are no longer available directly from the “cpython” namespace, but only from “cpython.datetime”. This is the correct way of doing it because the declarations refer to a standard library module, not the core CPython C-API itself.
memoryviewtype name no longer shows up in the module dict of modules that use memory views. This fixes trac ticket 775.
restrictcould accidentally be seen by the GNU C++ compiler. It is now specially handled for both GCC and MSVC.
c_string_encodingto more easily and automatically convert between C strings and the different Python string types.
Py_TPFLAGS_HAVE_VERSION_TAGis enabled by default on extension types and can be disabled using the
__annotations__attribute (PEP 3107).
Py_UNICODE*coerces from and to Python unicode strings. This is helpful when talking to Windows APIs, which use compatible wchar_t arrays for strings. Note that the
Py_UNICODEtype is otherwise deprecated as of CPython 3.3.
isinstance(obj, basestring)is optimised. In Python 3 it only tests for instances of
basestringbuiltin is mapped to
unicode) when compiling the generated C code under Python 3.
@cython.freelist(N)creates a static freelist of N instances for an extension type, thus avoiding the costly allocation step if possible. This can speed up object instantiation by 20-30% in suitable scenarios. Note that freelists are currently only supported for base types, not for types that inherit from others.
Type.__new__(Type)idiom has gained support for passing arguments. It is also a bit faster for types defined inside of the module.
.view*()(requires Python 2.7) are automatically mapped to the equivalent keys/values/items methods in Python 3 for typed dictionaries.
raise Exception() from Nonesuppresses the exception context in Py3.3.
exec(tuple)syntax is supported in Py2 code.
getitemprotocol is used instead of the
getsliceprotocol (especially in Python 3), i.e.
Nonevalues for missing bounds instead of
[0,maxsize]. It is also a bit faster in some cases, e.g. for constant bounds. This fixes trac ticket 636.
__defaults__attribute was not writable for Cython implemented 函数。
__kwdefaults__(which was not implemented). Both are available for Cython implemented functions now, as specified in Python 3.x.
yieldworks inside of
with gilsections. It previously lead to a crash. This fixes trac ticket 803.
*args) crashed when being called. This fixes trac ticket 804.
dir()without arguments previously returned an unsorted list, which now gets sorted as expected.
dict.values()no longer return lists in Python 3.
except-asclause now deletes the exception in Python 3 mode.
overflowcheckwhich raises an OverflowException when arithmetic with C ints overflow. This has a modest performance penalty, but is much faster than using Python ints.
constdeclarations are supported in the language.
cdef __weakref__attribute) generated incorrect deallocation code.
cythonize()gained a best effort compile mode that can be used to simply ignore .py files that fail to compile.
The availability of type inference by default means that Cython will also infer the type of pointers on assignments. Previously, code like this:
cdef char* s = ... untyped_variable = s
would convert the char* to a Python bytes string and assign that. This is no longer the case and no coercion will happen in the example above. The correct way of doing this is through an explicit cast or by typing the target variable, i.e.
cdef char* s = ... untyped_variable1 = <bytes>s untyped_variable2 = <object>s cdef object py_object = s cdef bytes bytes_string = s
bool is no longer a valid type name by default. The problem is that it’s not clear whether bool should refer to the Python type or the C++ type, and expecting one and finding the other has already led to several hard-to-find bugs. Both types are available for importing: you can use from cpython cimport bool for the Python bool type, and from libcpp cimport bool for the C++ type. bool is still a valid object by default, so one can still write bool(x).
is now correctly typed to take a
rather than an
There’s now native complex floating point support! C99 complex will be used if complex.h is included, otherwise explicit complex arithmetic working on all C compilers is used. [Robert Bradshaw]
cdef double complex a = 1 + 0.3j cdef np.ndarray[np.complex128_t, ndim=2] arr = \ np.zeros(10, np.complex128)
Cython can now generate a main()-method for embedding of the Python interpreter into an executable (see #289) [Robert Bradshaw]
@wraparound directive (another way to disable arr[idx] for negative idx) [Dag Sverre Seljebotn]
Correct support for NumPy record dtypes with different alignments, and “cdef packed struct” support [Dag Sverre Seljebotn]
@callspec directive, allowing custom calling convention macros [Lisandro Dalcin]