How to get outer class name from an inner class?

Adam Skutt askutt at gmail.com
Wed May 9 06:30:51 EDT 2012


On May 8, 4:05 pm, John Gordon <gor... at panix.com> wrote:
> I'm trying to come up with a scheme for organizing exceptions in
> my application.
>
> Currently, I'm using a base class which knows how to look up the text
> of a specific error in a database table, keyed on the error class name.
>
> The base class looks like this:
>
> class ApplicationException(Exception):
>     """Base class for application-specific errors."""
>
>     def get_message(self):
>         """Return the error message associated with this class name."""
>
>         class_name = self.__class__.__name__
>         return UserMessage.objects.get(key=class_name).text
>
> And then I define a bunch of subclasses which all have different names:
>
> class QuestionTooShortError(NetIDAppsError):
>     """User entered a security question which is too short."""
>     pass
>
> class QuestionTooLongError(NetIDAppsError):
>     """User entered a security question which is too long."""
>     pass
>
> This scheme works, but I'd like to make it more streamlined.  Specifically,
> I'd like to group the classes underneath a parent class, like so:
>
> class Question(ApplicationException):
>
>     class TooShort(ApplicationException):
>         pass
>
>     class TooLong(ApplicationException):
>         pass
>
> This will make it easier in the future for organizing lots of sub-errors.

It's no more or less organized than using a module, so use a module.
This is why they exist, after all.

That being said, this seems like a bad idea to me: this is a lot of
code and types just for a message lookup!  Exception types should
usually be created based on what you expect users to catch, not based
on what you could throw.  If all of these exceptions will be handled
in the same way, then they shouldn't be distinct types.

Adam



More information about the Python-list mailing list