Wrapping libraries with setup and teardown functions

23 views
Skip to first unread message

Ghislain Vaillant

unread,
Jul 23, 2017, 8:47:44 AM7/23/17
to python-cffi
I am in the process of writing a Python interface to a C library, which API contains setup (init) and teardown (cleanup) functions for resource management.

What's the usual pattern to handle this? Wrapping the `ffi` and `lib` into a class? a context manager? Are there examples of this you guys are aware of?

Cheers,
Ghis

Ghislain Vaillant

unread,
Aug 10, 2017, 6:47:55 AM8/10/17
to python-cffi
Le dimanche 23 juillet 2017 13:47:44 UTC+1, Ghislain Vaillant a écrit :
I am in the process of writing a Python interface to a C library, which API contains setup (init) and teardown (cleanup) functions for resource management.

What's the usual pattern to handle this? Wrapping the `ffi` and `lib` into a class? a context manager? Are there examples of this you guys are aware of?

Any ideas? Is it such an unusual case?

Matthias Geier

unread,
Aug 10, 2017, 8:53:24 AM8/10/17
to pytho...@googlegroups.com
I guess it depends if you want to expose those setup and teardown
functions to the users of your Python wrapper or not.

If not, you can still choose if you want to initialize your library at
import time (and clean up when the interpreter exits) or if you want
to create a class (which could be used as a context manager) or you
can wrap every single function call with a setup/teardown.

As an example (but I don't know if it's a good one), you can have a
look at my "sounddevice" module:
https://github.com/spatialaudio/python-sounddevice/blob/master/sounddevice.py
It initializes the underlying C library at import time and uses the
"atexit" module to register an exit handler.

Another example (still don't know if a good one) would be my "jack"
module: https://github.com/spatialaudio/jackclient-python/blob/master/jack.py
There is a "Client" class which does some initialization in __init__()
and it has a close() function for cleanup. The class can also be used
as a context manager.

cheers,
Matthias

> Cheers,
> Ghis
Reply all
Reply to author
Forward
0 new messages