Context manager, atexit processing, and PEP 3143 DaemonContext.close

Ben Finney ben+python at benfinney.id.au
Sat May 16 23:20:39 EDT 2009


Carl Banks <pavlovevidence at gmail.com> writes:

> There's already precedent for what to do in the Python library.
> 
> Python 2.5.2 (r252:60911, Jan  4 2009, 17:40:26)
> [GCC 4.3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> f = open('somefile')
> >>> f.close()
> >>> f.close()
> >>> f.close()
> >>> f.close()

Yes, that's a precedent in favour of “silently return immediately when
closing an already-closed DaemonContext”. I'm not about to assume that
it's the *only* relevant precedent.

> Is a context manager really necessary here? It's not like daemon
> processes can reattach themselves to the terminal when they're done
> being a daemon. What's the use case for being able to partially clean
> up before program exit?

The use case is::

    pidfile = MyChoiceOfLockFile()
    daemon_context = daemon.DaemonContext(pidfile=pidfile)

    with daemon_context:
        do_main_processing()

which could easily become something like::

    beans_resource = crunchy_init()

    with beans_resource:

        spam_resource = crispy_init()

        pidfile = MyChoiceOfLockFile()
        daemon_context = daemon.DaemonContext(pidfile=pidfile)

        with daemon_context:
            do_main_processing()

        spam_resource.cleanup()

In other words, the DaemonContext has a specific job, and is easier to
use if it can be relied on to clean up its own stuff via a context
manager; but the larger program could easily have other things (in the
example above, both of `spam_resource` and `beans_resource`) it needs to
clean up apart from just the daemon context.

-- 
 \     “We reserve the right to serve refuse to anyone. ” —restaurant, |
  `\                                                             Japan |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list