del an imported Class at EOF... why?

Carl Banks pavlovevidence at
Wed Oct 7 23:39:47 CEST 2009

On Oct 7, 2:31 am, Ryan <heni... at> wrote:
> Thanks everyone for your insight. I'm going to have to agree with the
> paranoid desire to prevent people importing his module and then using
> the
> classes he imports from elsewhere (I'm not ruling out the lead paint
> theory until I can gather more evidence).

It's wasted effort.  Python isn't really designed to have totally
clean namespaces.  A base class can be deleted at the end of a module
because it's only used while the module is being imported, but lots of
other symbols can't.  You can't delete any global that's used in a
function, that means most imported modules or functions have to remain
in the module's namespace, and usually there are a lot more of them
than there are deletable base classes.

Given that you can't generally have an externally clean namespace, why
put forth such effort just to delete one or two names?

The right thing to do is to advertise which symbols are external with
__all__ (or, as judgment call, to use leading underscore on all
internal symbols).

There are some tricks you could use to keep __all__ up-to-date, for
instance you can use this idiom to automatically add anything defined
between two points to __all__ (though it can be subject to name

## do all your imports here

_internals = set(globals())

## define all your functions/classes/constants here

_allnames = set(globals())
__all__ = list(x for x in _allnames-_internals
               if not x.startswith('_'))
del _internals, _allnames
# del ok here because this does free memory

Carl Banks

More information about the Python-list mailing list