SlideShare a Scribd company logo
1 of 50
Download to read offline
Extending Python
Francisco Fernandez Castano
upclose.me
francisco.fernandez.castano@gmail.com @fcofdezc
January 31, 2015
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 1 / 50
Overview
1 Motivations
2 Guidelines
3 Native extensions
4 CTypes
5 CFFI
6 Conclusions
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 2 / 50
Caution
Huge topic
Toy examples
Unix ĈPython centric
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 3 / 50
Motivation
Why write in C?
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 4 / 50
Motivation
Speed
Using legacy code
Integration
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 5 / 50
Motivation
Why is Python slow?
Interpretation overhead
Boxed arithmetic and automatic overflow handling
Dynamic dispatch of operations
Dynamic lookup of methods and attributes
Everything can change on runtime
Extreme introspective and reflective capabilities
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 6 / 50
Motivation
Speed
Using legacy code
Integration
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 7 / 50
Motivation
Speed
Using legacy code
Integration
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 8 / 50
Shared libraries
Single copy in memory
Runtime load
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 9 / 50
Native extensions
C API
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 10 / 50
Native extensions
Hello world, Newton method
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 11 / 50
Native extensions
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 12 / 50
Native extensions
#include "Python.h"
static PyObject *
newton(PyObject *self , PyObject *args)
{
float guess;
float x;
if (! PyArg_ParseTuple (args , "ff", &guess , &x))
return NULL;
while (fabs(powf(guess , 2) - x) > 0.01)
{
guess = ((x / guess) + guess) / 2;
}
return Py_BuildValue("f", guess );
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 13 / 50
Native extensions
static PyMethodDef
module_functions [] = {
{"newton", newton , METH_VARARGS , "Newton method."},
{NULL}
};
PyMODINIT_FUNC
initnewton(void)
{
Py_InitModule3 ("newton", module_functions , "Newton");
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 14 / 50
Native extensions
from distutils.core import setup , Extension
setup(name=’codemotion ’,
version =1.0,
ext_modules =[
Extension(’newton ’, [’newton.c’])])
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 15 / 50
Native extensions
Python 2.7.5 (default , Nov 3 2014, 14:26:24)
[GCC 4.8.3 20140911 (Red Hat 4.8.3 -7)] on linux2
>>> import newton
>>> newton.newton (1, 2)
1.4166667461395264
>>>
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 16 / 50
How?
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 17 / 50
Native extensions
NAME
dlopen --load and link a dynamic library or bundle
SYNOPSIS
#include <dlfcn.h>
void*
dlopen(const char* path , int mode );
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 18 / 50
Native extensions
$ nm -g newton.so
00000000002010 a0 B __bss_start
w __cxa_finalize@@GLIBC_2 .2.5
00000000002010 a0 D _edata
00000000002010 a8 B _end
0000000000000944 T _fini
w __gmon_start__
00000000000006 d0 T _init
0000000000000920 T initnewton
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
w _Jv_RegisterClasses
U PyArg_ParseTuple
U Py_BuildValue
U Py_InitModule4_64
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 19 / 50
Native extensions
cpython/Python/dynload shlib.c
handle = dlopen(pathname , dlopenflags );
if (handle == NULL) {
const char *error = dlerror ();
if (error == NULL)
error = "unknown dlopen () error";
PyErr_SetString (PyExc_ImportError , error );
return NULL;
}
if (fp != NULL && nhandles < 128)
handles[nhandles ++]. handle = handle;
p = (dl_funcptr) dlsym(handle , funcname );
return p;
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 20 / 50
Native extensions
Memory management
Manual memory management
Python GC - RC
Cycle detector
Py INCREF(x) Py DECREF(x)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 21 / 50
Native extensions
Error management
Return NULL as a convention
Register exceptions
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 22 / 50
Native extensions
Error management
if (err < 0) {
PyErr_SetString (PyExc_Exception , "Err");
return NULL;
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 23 / 50
Native extensions
Python 3 differences
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT ,
"newton",
"newton module doc string",
-1,
module_functions ,
NULL ,
NULL ,
NULL ,
NULL };
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 24 / 50
Native extensions
Python 3 differences
PyMODINIT_FUNC
PyInit_sum(void)
{
PyModule_Create (& examplemodule );
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 25 / 50
CTypes
Advanced FFI for Python
Allows call functions from Shared libs
Create, access, manipulate C data types
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 26 / 50
CTypes
Types correspondence
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 27 / 50
CTypes
Structs
from ctypes import *
class POINT(Structure ):
_fields_ = [("x", c_int), ("y", c_int )]
class RECT(Structure ):
_fields_ = [("upperleft", POINT),
("lowerright", POINT )]
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 28 / 50
CTypes
Example
Implemented fibonacci as c function
Map as Python code
Measure differences between Python and C
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 29 / 50
CTypes
int fib(int n){
if (n < 2)
return n;
else
return fib(n - 1) + fib(n - 2);
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 30 / 50
CTypes
import ctypes
lib_fib = ctypes.CDLL("libfib.so")
def ctypes_fib(n):
return lib_fib.fib(ctypes.c_int(n))
def py_fib(n):
if n < 2:
return n
else:
return py_fib(n-1) + py_fib(n-2)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 31 / 50
CTypes
In [3]: %timeit fib.ctypes_fib (20)
10000 loops , best of 3: 63.8 micro s per loop
In [4]: %timeit fib.py_fib (20)
100 loops , best of 3: 3.62 ms per loop
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 32 / 50
CTypes
Fortran example
Use of existing fortran code
Take random code at github
https://github.com/astrofrog/fortranlib
Wrap using ctypes
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 33 / 50
CTypes
Fortran example
real(dp) function mean_dp(x, mask)
implicit none
real(dp),intent(in) :: x(:)
logical ,intent(in),optional :: mask (:)
if(present(mask )) then
mean_dp = sum(x, mask=mask )/ size(x)
else
mean_dp = sum(x)/ size(x)
end if
end function mean_dp
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 34 / 50
CTypes
Fortran example
gfortran -fPIC -shared statistic.f90 -o lib_statistics .so
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 35 / 50
CTypes
Fortran example
bin git:( master) -> nm -g lib_statistics .so
001 eab T ___lib_statistics_MOD_clipped_mean_dp
000 afc T ___lib_statistics_MOD_clipped_mean_sp
00306c T ___lib_statistics_MOD_mean_dp
001 c55 T ___lib_statistics_MOD_mean_sp
002 db0 T ___lib_statistics_MOD_median_dp
0019 b0 T ___lib_statistics_MOD_median_sp
002544 T ___lib_statistics_MOD_quantile_dp
00115a T ___lib_statistics_MOD_quantile_sp
002299 T ___lib_statistics_MOD_variance_dp
000 ec3 T ___lib_statistics_MOD_variance_sp
U __gfortran_arandom_r4
U __gfortran_arandom_r8
U __gfortran_os_error
U __gfortran_pack
U __gfortran_pow_i4_i4
U __gfortran_runtime_error
U __gfortran_runtime_error_at
U __gfortran_st_write
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 36 / 50
CTypes
Fortran example
from ctypes import *
# Statistics fortran lib
st_lib = CDLL(’lib_statistics.so’)
mean = st_lib. __lib_statistics_MOD_mean_dp
mean.argtypes = [POINTER(c_float *2)]
mean.restype = c_float
vals = (c_float *2)(2.0 , 3.0)
print mean(vals)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 37 / 50
CTypes
CTypes source
cpython/Modules/ ctypes/callproc.c
static PyObject *py_dl_open(PyObject *self , PyObject *args)
{
char *name;
void * handle;
#ifdef RTLD_LOCAL
int mode = RTLD_NOW | RTLD_LOCAL;
#else
/* cygwin doesn ’t define RTLD_LOCAL */
int mode = RTLD_NOW;
#endif
if (! PyArg_ParseTuple (args , "z|i:dlopen", &name , &mode ))
return NULL;
mode |= RTLD_NOW;
handle = ctypes_dlopen(name , mode );
.
return PyLong_FromVoidPtr (handle );
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 38 / 50
CFFI
Advanced FFI for Python
Allows call functions from Shared libs
Create, access, manipulate C data types
Both API and ABI access
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 39 / 50
CFFI
Mostly the same as CTypes
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 40 / 50
CFFI
Recommended way to extend PyPy
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 41 / 50
CFFI
ABI
from cffi import FFI
ffi = FFI()
ffi.cdef(""" int printf(const char *format , ...); """)
C = ffi.dlopen(None)
arg = ffi.new("char []", "world")
C.printf("hi there , %s!n", arg)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 42 / 50
CFFI
ABI- Fibonacci
from cffi import FFI
ffi = FFI()
ffi.cdef(""" int fib(int n);""")
libfib = ffi.dlopen(’libfib.so’)
libfib.fib (10)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 43 / 50
CFFI
API Level
import cffi
ffi = cffi.FFI()
ffi.cdef(""" int fib(int n);""")
lib = ffi.verify(r’’’
int fib(int n){
if ( n < 2 )
return n;
else
return fib(n-1) + fib(n -2);
}’’’)
print lib.fib (10)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 44 / 50
CFFI
API Level
import cffi
ffi = cffi.FFI()
ffi.cdef(""" int fib(int n);""")
lib = ffi.verify(r’’’
int fib(int n){
if ( n < 2 )
return n;
else
return fib(n-1) + fib(n -2);
}’’’)
print lib.fib(’asd’)
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 45 / 50
CFFI
API Level
Traceback (most recent call last ):
File "fib.py", line 16, in <module >
print lib.fib("asd")
TypeError: an integer is required
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 46 / 50
CFFI
API Level
from cffi import FFI
ffi = FFI()
ffi.cdef(""" typedef struct { float x, y; } point;""")
point = ffi.new("point *")
point.x = 2.0
point.y = 3.0
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 47 / 50
CFFI
Internals
cffi/c/ cffi backend.c
static PyObject *
b_load_library (PyObject *self , PyObject *args)
{
void *handle;
DynLibObject *dlobj;
if (( flags & (RTLD_NOW | RTLD_LAZY )) == 0)
flags |= RTLD_NOW;
printable_filename = filename_or_null ? filename_or_null :
handle = dlopen(filename_or_null , flags );
dlobj = PyObject_New(DynLibObject , &dl_type );
dlobj ->dl_handle = handle;
dlobj ->dl_name = strdup( printable_filename );
return (PyObject *) dlobj;
}
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 48 / 50
Conclusions
Three different ways
Same principles
Less portable - More portable
Harder - Easier
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 49 / 50
Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 50 / 50

More Related Content

What's hot

Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Edureka!
 
CrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for BeginnersCrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for BeginnersOlga Scrivner
 
Python教程 / Python tutorial
Python教程 / Python tutorialPython教程 / Python tutorial
Python教程 / Python tutorialee0703
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Python interview questions
Python interview questionsPython interview questions
Python interview questionsPragati Singh
 
Python Programming - XIII. GUI Programming
Python Programming - XIII. GUI ProgrammingPython Programming - XIII. GUI Programming
Python Programming - XIII. GUI ProgrammingRanel Padon
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Edureka!
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for studentsCorey McCreary
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | EdurekaEdureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
The str/bytes nightmare before python2 EOL
The str/bytes nightmare before python2 EOLThe str/bytes nightmare before python2 EOL
The str/bytes nightmare before python2 EOLKir Chou
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...Edureka!
 

What's hot (20)

Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
CrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for BeginnersCrashCourse: Python with DataCamp and Jupyter for Beginners
CrashCourse: Python with DataCamp and Jupyter for Beginners
 
Python教程 / Python tutorial
Python教程 / Python tutorialPython教程 / Python tutorial
Python教程 / Python tutorial
 
Python
Python Python
Python
 
Python lec1
Python lec1Python lec1
Python lec1
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Python interview questions
Python interview questionsPython interview questions
Python interview questions
 
Python Programming - XIII. GUI Programming
Python Programming - XIII. GUI ProgrammingPython Programming - XIII. GUI Programming
Python Programming - XIII. GUI Programming
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for students
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
Python training
Python trainingPython training
Python training
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
The str/bytes nightmare before python2 EOL
The str/bytes nightmare before python2 EOLThe str/bytes nightmare before python2 EOL
The str/bytes nightmare before python2 EOL
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
 

Viewers also liked

Knowing your garbage collector - FOSDEM 2015
Knowing your garbage collector - FOSDEM 2015Knowing your garbage collector - FOSDEM 2015
Knowing your garbage collector - FOSDEM 2015fcofdezc
 
Graph databases - EuroPython 2014
Graph databases - EuroPython 2014Graph databases - EuroPython 2014
Graph databases - EuroPython 2014fcofdezc
 
Knowing your garbage collector - PyCon Italy 2015
Knowing your garbage collector - PyCon Italy 2015Knowing your garbage collector - PyCon Italy 2015
Knowing your garbage collector - PyCon Italy 2015fcofdezc
 
Knowing your Garbage Collector / Python Madrid
Knowing your Garbage Collector / Python MadridKnowing your Garbage Collector / Python Madrid
Knowing your Garbage Collector / Python Madridfcofdezc
 
STM on PyPy
STM on PyPySTM on PyPy
STM on PyPyfcofdezc
 
Understanding PyPy - PyConEs 14
Understanding PyPy - PyConEs 14Understanding PyPy - PyConEs 14
Understanding PyPy - PyConEs 14fcofdezc
 
Extending Python - Codemotion Milano 2014
Extending Python - Codemotion Milano 2014Extending Python - Codemotion Milano 2014
Extending Python - Codemotion Milano 2014fcofdezc
 
Historia Del Crsistianismo
Historia Del CrsistianismoHistoria Del Crsistianismo
Historia Del Crsistianismoantso
 

Viewers also liked (8)

Knowing your garbage collector - FOSDEM 2015
Knowing your garbage collector - FOSDEM 2015Knowing your garbage collector - FOSDEM 2015
Knowing your garbage collector - FOSDEM 2015
 
Graph databases - EuroPython 2014
Graph databases - EuroPython 2014Graph databases - EuroPython 2014
Graph databases - EuroPython 2014
 
Knowing your garbage collector - PyCon Italy 2015
Knowing your garbage collector - PyCon Italy 2015Knowing your garbage collector - PyCon Italy 2015
Knowing your garbage collector - PyCon Italy 2015
 
Knowing your Garbage Collector / Python Madrid
Knowing your Garbage Collector / Python MadridKnowing your Garbage Collector / Python Madrid
Knowing your Garbage Collector / Python Madrid
 
STM on PyPy
STM on PyPySTM on PyPy
STM on PyPy
 
Understanding PyPy - PyConEs 14
Understanding PyPy - PyConEs 14Understanding PyPy - PyConEs 14
Understanding PyPy - PyConEs 14
 
Extending Python - Codemotion Milano 2014
Extending Python - Codemotion Milano 2014Extending Python - Codemotion Milano 2014
Extending Python - Codemotion Milano 2014
 
Historia Del Crsistianismo
Historia Del CrsistianismoHistoria Del Crsistianismo
Historia Del Crsistianismo
 

Similar to Extending Python - FOSDEM 2015

Extending Python, what is the best option for me?
Extending Python, what is the best option for me?Extending Python, what is the best option for me?
Extending Python, what is the best option for me?Codemotion
 
Knowing your Python Garbage Collector
Knowing your Python Garbage CollectorKnowing your Python Garbage Collector
Knowing your Python Garbage Collectorfcofdezc
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimeNational Cheng Kung University
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...South Tyrol Free Software Conference
 
File formats for Next Generation Sequencing
File formats for Next Generation SequencingFile formats for Next Generation Sequencing
File formats for Next Generation SequencingPierre Lindenbaum
 
Python update in 2018 #ll2018jp
Python update in 2018 #ll2018jpPython update in 2018 #ll2018jp
Python update in 2018 #ll2018jpcocodrips
 
Python Evolution
Python EvolutionPython Evolution
Python EvolutionQuintagroup
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in PythonMarc Garcia
 
data-microscopes
data-microscopesdata-microscopes
data-microscopesStephen Tu
 
Introduction to Python and Matplotlib
Introduction to Python and MatplotlibIntroduction to Python and Matplotlib
Introduction to Python and MatplotlibFrançois Bianco
 
PyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyCon Italia
 
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Artur Rodrigues
 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015Alina Dolgikh
 
Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientistsaeberspaecher
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasOswald Campesato
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in PythonAjay Ohri
 

Similar to Extending Python - FOSDEM 2015 (20)

Extending Python, what is the best option for me?
Extending Python, what is the best option for me?Extending Python, what is the best option for me?
Extending Python, what is the best option for me?
 
Knowing your Python Garbage Collector
Knowing your Python Garbage CollectorKnowing your Python Garbage Collector
Knowing your Python Garbage Collector
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
 
File formats for Next Generation Sequencing
File formats for Next Generation SequencingFile formats for Next Generation Sequencing
File formats for Next Generation Sequencing
 
Python update in 2018 #ll2018jp
Python update in 2018 #ll2018jpPython update in 2018 #ll2018jp
Python update in 2018 #ll2018jp
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in Python
 
data-microscopes
data-microscopesdata-microscopes
data-microscopes
 
Introduction to Python and Matplotlib
Introduction to Python and MatplotlibIntroduction to Python and Matplotlib
Introduction to Python and Matplotlib
 
PyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fast
 
Learn python
Learn pythonLearn python
Learn python
 
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook
Python na Infraestrutura 
MySQL do Facebook

Python na Infraestrutura 
MySQL do Facebook

 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015
 
Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientists
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and Keras
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in Python
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Extending Python - FOSDEM 2015

  • 1. Extending Python Francisco Fernandez Castano upclose.me francisco.fernandez.castano@gmail.com @fcofdezc January 31, 2015 Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 1 / 50
  • 2. Overview 1 Motivations 2 Guidelines 3 Native extensions 4 CTypes 5 CFFI 6 Conclusions Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 2 / 50
  • 3. Caution Huge topic Toy examples Unix ĈPython centric Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 3 / 50
  • 4. Motivation Why write in C? Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 4 / 50
  • 5. Motivation Speed Using legacy code Integration Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 5 / 50
  • 6. Motivation Why is Python slow? Interpretation overhead Boxed arithmetic and automatic overflow handling Dynamic dispatch of operations Dynamic lookup of methods and attributes Everything can change on runtime Extreme introspective and reflective capabilities Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 6 / 50
  • 7. Motivation Speed Using legacy code Integration Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 7 / 50
  • 8. Motivation Speed Using legacy code Integration Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 8 / 50
  • 9. Shared libraries Single copy in memory Runtime load Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 9 / 50
  • 10. Native extensions C API Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 10 / 50
  • 11. Native extensions Hello world, Newton method Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 11 / 50
  • 12. Native extensions Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 12 / 50
  • 13. Native extensions #include "Python.h" static PyObject * newton(PyObject *self , PyObject *args) { float guess; float x; if (! PyArg_ParseTuple (args , "ff", &guess , &x)) return NULL; while (fabs(powf(guess , 2) - x) > 0.01) { guess = ((x / guess) + guess) / 2; } return Py_BuildValue("f", guess ); } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 13 / 50
  • 14. Native extensions static PyMethodDef module_functions [] = { {"newton", newton , METH_VARARGS , "Newton method."}, {NULL} }; PyMODINIT_FUNC initnewton(void) { Py_InitModule3 ("newton", module_functions , "Newton"); } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 14 / 50
  • 15. Native extensions from distutils.core import setup , Extension setup(name=’codemotion ’, version =1.0, ext_modules =[ Extension(’newton ’, [’newton.c’])]) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 15 / 50
  • 16. Native extensions Python 2.7.5 (default , Nov 3 2014, 14:26:24) [GCC 4.8.3 20140911 (Red Hat 4.8.3 -7)] on linux2 >>> import newton >>> newton.newton (1, 2) 1.4166667461395264 >>> Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 16 / 50
  • 17. How? Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 17 / 50
  • 18. Native extensions NAME dlopen --load and link a dynamic library or bundle SYNOPSIS #include <dlfcn.h> void* dlopen(const char* path , int mode ); Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 18 / 50
  • 19. Native extensions $ nm -g newton.so 00000000002010 a0 B __bss_start w __cxa_finalize@@GLIBC_2 .2.5 00000000002010 a0 D _edata 00000000002010 a8 B _end 0000000000000944 T _fini w __gmon_start__ 00000000000006 d0 T _init 0000000000000920 T initnewton w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w _Jv_RegisterClasses U PyArg_ParseTuple U Py_BuildValue U Py_InitModule4_64 Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 19 / 50
  • 20. Native extensions cpython/Python/dynload shlib.c handle = dlopen(pathname , dlopenflags ); if (handle == NULL) { const char *error = dlerror (); if (error == NULL) error = "unknown dlopen () error"; PyErr_SetString (PyExc_ImportError , error ); return NULL; } if (fp != NULL && nhandles < 128) handles[nhandles ++]. handle = handle; p = (dl_funcptr) dlsym(handle , funcname ); return p; Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 20 / 50
  • 21. Native extensions Memory management Manual memory management Python GC - RC Cycle detector Py INCREF(x) Py DECREF(x) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 21 / 50
  • 22. Native extensions Error management Return NULL as a convention Register exceptions Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 22 / 50
  • 23. Native extensions Error management if (err < 0) { PyErr_SetString (PyExc_Exception , "Err"); return NULL; } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 23 / 50
  • 24. Native extensions Python 3 differences static struct PyModuleDef examplemodule = { PyModuleDef_HEAD_INIT , "newton", "newton module doc string", -1, module_functions , NULL , NULL , NULL , NULL }; Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 24 / 50
  • 25. Native extensions Python 3 differences PyMODINIT_FUNC PyInit_sum(void) { PyModule_Create (& examplemodule ); } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 25 / 50
  • 26. CTypes Advanced FFI for Python Allows call functions from Shared libs Create, access, manipulate C data types Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 26 / 50
  • 27. CTypes Types correspondence Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 27 / 50
  • 28. CTypes Structs from ctypes import * class POINT(Structure ): _fields_ = [("x", c_int), ("y", c_int )] class RECT(Structure ): _fields_ = [("upperleft", POINT), ("lowerright", POINT )] Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 28 / 50
  • 29. CTypes Example Implemented fibonacci as c function Map as Python code Measure differences between Python and C Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 29 / 50
  • 30. CTypes int fib(int n){ if (n < 2) return n; else return fib(n - 1) + fib(n - 2); } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 30 / 50
  • 31. CTypes import ctypes lib_fib = ctypes.CDLL("libfib.so") def ctypes_fib(n): return lib_fib.fib(ctypes.c_int(n)) def py_fib(n): if n < 2: return n else: return py_fib(n-1) + py_fib(n-2) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 31 / 50
  • 32. CTypes In [3]: %timeit fib.ctypes_fib (20) 10000 loops , best of 3: 63.8 micro s per loop In [4]: %timeit fib.py_fib (20) 100 loops , best of 3: 3.62 ms per loop Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 32 / 50
  • 33. CTypes Fortran example Use of existing fortran code Take random code at github https://github.com/astrofrog/fortranlib Wrap using ctypes Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 33 / 50
  • 34. CTypes Fortran example real(dp) function mean_dp(x, mask) implicit none real(dp),intent(in) :: x(:) logical ,intent(in),optional :: mask (:) if(present(mask )) then mean_dp = sum(x, mask=mask )/ size(x) else mean_dp = sum(x)/ size(x) end if end function mean_dp Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 34 / 50
  • 35. CTypes Fortran example gfortran -fPIC -shared statistic.f90 -o lib_statistics .so Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 35 / 50
  • 36. CTypes Fortran example bin git:( master) -> nm -g lib_statistics .so 001 eab T ___lib_statistics_MOD_clipped_mean_dp 000 afc T ___lib_statistics_MOD_clipped_mean_sp 00306c T ___lib_statistics_MOD_mean_dp 001 c55 T ___lib_statistics_MOD_mean_sp 002 db0 T ___lib_statistics_MOD_median_dp 0019 b0 T ___lib_statistics_MOD_median_sp 002544 T ___lib_statistics_MOD_quantile_dp 00115a T ___lib_statistics_MOD_quantile_sp 002299 T ___lib_statistics_MOD_variance_dp 000 ec3 T ___lib_statistics_MOD_variance_sp U __gfortran_arandom_r4 U __gfortran_arandom_r8 U __gfortran_os_error U __gfortran_pack U __gfortran_pow_i4_i4 U __gfortran_runtime_error U __gfortran_runtime_error_at U __gfortran_st_write Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 36 / 50
  • 37. CTypes Fortran example from ctypes import * # Statistics fortran lib st_lib = CDLL(’lib_statistics.so’) mean = st_lib. __lib_statistics_MOD_mean_dp mean.argtypes = [POINTER(c_float *2)] mean.restype = c_float vals = (c_float *2)(2.0 , 3.0) print mean(vals) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 37 / 50
  • 38. CTypes CTypes source cpython/Modules/ ctypes/callproc.c static PyObject *py_dl_open(PyObject *self , PyObject *args) { char *name; void * handle; #ifdef RTLD_LOCAL int mode = RTLD_NOW | RTLD_LOCAL; #else /* cygwin doesn ’t define RTLD_LOCAL */ int mode = RTLD_NOW; #endif if (! PyArg_ParseTuple (args , "z|i:dlopen", &name , &mode )) return NULL; mode |= RTLD_NOW; handle = ctypes_dlopen(name , mode ); . return PyLong_FromVoidPtr (handle ); } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 38 / 50
  • 39. CFFI Advanced FFI for Python Allows call functions from Shared libs Create, access, manipulate C data types Both API and ABI access Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 39 / 50
  • 40. CFFI Mostly the same as CTypes Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 40 / 50
  • 41. CFFI Recommended way to extend PyPy Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 41 / 50
  • 42. CFFI ABI from cffi import FFI ffi = FFI() ffi.cdef(""" int printf(const char *format , ...); """) C = ffi.dlopen(None) arg = ffi.new("char []", "world") C.printf("hi there , %s!n", arg) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 42 / 50
  • 43. CFFI ABI- Fibonacci from cffi import FFI ffi = FFI() ffi.cdef(""" int fib(int n);""") libfib = ffi.dlopen(’libfib.so’) libfib.fib (10) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 43 / 50
  • 44. CFFI API Level import cffi ffi = cffi.FFI() ffi.cdef(""" int fib(int n);""") lib = ffi.verify(r’’’ int fib(int n){ if ( n < 2 ) return n; else return fib(n-1) + fib(n -2); }’’’) print lib.fib (10) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 44 / 50
  • 45. CFFI API Level import cffi ffi = cffi.FFI() ffi.cdef(""" int fib(int n);""") lib = ffi.verify(r’’’ int fib(int n){ if ( n < 2 ) return n; else return fib(n-1) + fib(n -2); }’’’) print lib.fib(’asd’) Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 45 / 50
  • 46. CFFI API Level Traceback (most recent call last ): File "fib.py", line 16, in <module > print lib.fib("asd") TypeError: an integer is required Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 46 / 50
  • 47. CFFI API Level from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct { float x, y; } point;""") point = ffi.new("point *") point.x = 2.0 point.y = 3.0 Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 47 / 50
  • 48. CFFI Internals cffi/c/ cffi backend.c static PyObject * b_load_library (PyObject *self , PyObject *args) { void *handle; DynLibObject *dlobj; if (( flags & (RTLD_NOW | RTLD_LAZY )) == 0) flags |= RTLD_NOW; printable_filename = filename_or_null ? filename_or_null : handle = dlopen(filename_or_null , flags ); dlobj = PyObject_New(DynLibObject , &dl_type ); dlobj ->dl_handle = handle; dlobj ->dl_name = strdup( printable_filename ); return (PyObject *) dlobj; } Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 48 / 50
  • 49. Conclusions Three different ways Same principles Less portable - More portable Harder - Easier Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 49 / 50
  • 50. Francisco Fernandez Castano (@fcofdezc) Extending Python January 31, 2015 50 / 50