Best way to disconnect from ldap?

Chris Rebert clp2 at
Wed Mar 21 21:34:29 CET 2012

On Wed, Mar 21, 2012 at 12:30 PM, John Gordon <gordon at> wrote:
> I'm writing an application that interacts with ldap, and I'm looking
> for advice on how to handle the connection.  Specifically, how to
> close the ldap connection when the application is done.
> I wrote a class to wrap an LDAP connection, similar to this:
>    import ldap
>    import ConfigParser
>    class MyLDAPWrapper(object):
>        def __init__(self):
>            config = ConfigParser.SafeConfigParser()
>  'sample.conf')
>            uri = config.get('LDAP', 'uri')
>            user = config.get('LDAP', 'user')
>            password = config.get('LDAP', 'password')
>            self.ldapClient = ldap.initialize(uri)
>            self.ldapClient.simple_bind_s(user, password)
> My question is this: what is the best way to ensure the ldap connection
> gets closed when it should?  I could write an explicit close() method,
> but that seems a bit messy; there would end up being lots of calls to
> close() scattered around in my code (primarily inside exception handlers.)
> Or I could write a __del__ method:
>        def __del__(self):
>            self.ldapClient.unbind_s()
> This seems like a much cleaner solution, as I don't ever have to worry
> about closing the connection; it gets done automatically.

Yes, but not necessarily in a timely manner. Since its uses reference
counting, CPython /just so happens/ to finalize
non-cyclically-referenced objects promptly when they go out of scope,
but Python-the-language makes no such guarantee, and indeed some of
the other Python implementations explicitly disclaim that there may be
a significant delay before finalization is performed.

> I haven't ever used __del__ before.  Are there any 'gotchas' I need to
> worry about?

In addition to the aforementioned problem regarding portability to
other Python implementations, see also the Warning box under:

I concur with J.'s context manager suggestion.


More information about the Python-list mailing list