How to get outer class name from an inner class?

alex23 wuwei23 at gmail.com
Wed May 9 02:31:04 EDT 2012


On May 9, 6:05 am, John Gordon <gor... at panix.com> wrote:
> 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.
>
> 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?

This might do the trick:

  import inspect

  def exception_members(scope):
      classes = (m[1] for m in inspect.getmembers(scope,
inspect.isclass))
      return set(
          c for c in classes if Exception in c.__mro__
      )

  class ApplicationException(Exception):
      @property
      def outer_scope(self):
          for _class in
exception_members(inspect.getmodule(self.__class__)):
              if self.__class__ in exception_members(_class):
                  return _class

      def get_message(self):
          scope = self.outer_scope
          class_name = scope.__name__ + '.' if scope else ''
          class_name += self.__class__.__name__
          return class_name

When get_message is run, it looks in the module where the exception
was defined for any new classes derived from Exception, then looks at
the members of each of those to see if it matches the current object's
class.

Not really well tested, so beware :)



More information about the Python-list mailing list