Simplifying anonymous inner classes?

Tim Chase python.list at tim.thechases.com
Sat Nov 1 13:13:16 CET 2008


I've got code similar to the following

  class Action:
    def __init__(self, ...):  pass
    def __call__(self, ...):  pass
    def get_help(self, ...):  pass

  class Backend:
    class _Load(Action):
      def __init__(self, ...): pass # override1
      def __call__(self, ...): pass # override1
      def get_help(self, ...): pass # override1
    load = _Load(...)
    class _Run(Action):
      def __call__(self, ...): pass # override2
      def get_help(self, ...): pass # override2
    run = _Run(...)

  class DatabaseBackend(Backend):
    class _Frob(Action):
      def __init__(self, ...): pass # override3
      def __call__(self, ...): pass # override3
      def get_help(self, ...): pass # override3
    frob = _Frob(...)

In certain other languages, I might reach for an anonymous inner 
class -- however, I don't see any way to do something like

  class Backend:
    load = (class Action:
      def __init__(self, ...): pass # override1
      def __call__(self, ...): pass # override1
      def get_help(self, ...): pass # override1
      )(...args to __init__...)
    run = ...

It seems silly to define the inner classes _Load and _Run just to 
create a single instance of them (and for all it matters the 
_Load and _Run could be promptly deleted from the containing 
namespace immediately after instantiation).  Method 
implementations are sufficiently complex that a lambda won't 
suffice (or if they would, they're beyond my know-how).

Is there a more Pythonic way to instantiate sub-classes and 
provide instance-specific implementations without the overhead of 
an unused "anonymous" class cluttering my code/namespace?

Thanks,

-tkc


PS: part of the aim is to have properties that can be discovered 
through introspection, know how to provide help on themselves, 
and have a protocol for parameter-discovery for the __call__ method.







More information about the Python-list mailing list