[Tutor] custom error classes: how many of them does one need?

eryksun eryksun at gmail.com
Fri Jul 5 04:40:03 CEST 2013


On Thu, Jul 4, 2013 at 3:40 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> a common practice is to create a base class for exceptions defined by
> that module, and subclass that to create specific exception classes
> for different error conditions"

Look to the reorganization of OSError in 3.3 as a model, specifically
the rationale regarding fine-grained exceptions:

http://www.python.org/dev/peps/pep-3151
http://docs.python.org/3/library/exceptions#exception-hierarchy

> global retcodes
> retcodes = {0: "OK", 1: "Error_X", 2: "Error_Y"}

FYI, the "global" declaration here is redundant. At module level,
locals and globals use the same dict. So there's no point in forcing
the compiler to use STORE_GLOBAL instead of the default STORE_LOCAL.
It would only be necessary if you were doing something out of the
ordinary, such as using exec with globals and locals set to different
dicts:

    >>> nsglobals, nslocals = {}, {}
    >>> exec 'def f(): pass' in nsglobals, nslocals
    >>> 'f' in nsglobals
    False
    >>> nslocals['f'].__globals__ is nsglobals
    True

Now with a "global f" declaration:

    >>> nsglobals, nslocals = {}, {}
    >>> exec 'global f\ndef f(): pass' in nsglobals, nslocals
    >>> nsglobals['f'].__globals__ is nsglobals
    True


More information about the Tutor mailing list