How to get outer class name from an inner class?

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Wed May 9 03:56:25 EDT 2012


Am 08.05.2012 22:05, schrieb John Gordon:
[...]
> class QuestionTooShortError(ApplicationException):
>     """User entered a security question which is too short."""
>     pass
> 
> class QuestionTooLongError(ApplicationException):
>     """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.

What is it that this "parent class" represents? What is the relation
between class Question and class TooShort? In general terms, it isn't
even a parent class but just an outer class, a parent class implies that
child classes inherit from it.

I think that you're going about this the wrong way, and that a module
represents much better what you are trying to express here. Your code
actually looks a bit like it was written with a strong Java or C++
background, could that be the case?


> My problem is this: the get_message() method in the base class only knows
> the current class name, i.e. "TooShort" or "TooLong".  But that's not
> enough; I also need to know the outer class name, i.e. "Question.TooShort"
> or "Question.TooLong".  How do I get the outer class name?

# in module "Question"
class _Exception(ApplicationException):
    def get_message(self):
        return self._lookup_message("Question." +
			            self.__class__.__name__)
class TooLong(_Exception):
    pass


You might even be able to look up the module name instead of hard-coding
it in one place.

Uli



More information about the Python-list mailing list