このコード スニペットは、python 3.6.4 では問題なく動作しますが、.pyx ファイルに存在すると移植性の問題が発生します。Cython で python 3.5.1+ バイトを最適にフォーマットする方法を理解するために、いくつかの助けを借りることができます。
編集: DavidW のコメントに照らしてこれを変更します。
以下は、ipythonの下のpython 3.6.4で動作します
def py_foo():
bytes_1 = b'bytes 1'
bytes_2 = b'bytes 2'
return b'%(bytes_1)b %(bytes_2)b' % {
b'bytes_1': bytes_1,
b'bytes_2': bytes_2}
期待どおり、これにより次の結果が得られます。
print(py_foo())
b'bytes 1 bytes 2'
関数の名前、宣言された戻り値の型、および 2 つの変数の宣言であるコードへの唯一の変更で cython を使用します。
%load_ext Cython
# Cython==0.28
に続く:
%%cython
cpdef bytes cy_foo():
cdef:
bytes bytes_1, bytes_2
bytes_1 = b'bytes 1'
bytes_2 = b'bytes 2'
return b'%(bytes_1)b %(bytes_2)b' % {
b'bytes_1': bytes_1,
b'bytes_2': bytes_2}
結果:
Error compiling Cython file:
....
return b'%(bytes_1)b %(bytes_2)b' % {
^
..._cython_magic_b0aa5be86bdfdf75b98df1af1a2394af.pyx:7:38: Cannot convert 'basestring' object to bytes implicitly. This is not portable.
-djv