Simplifying anonymous inner classes?

Carl Banks pavlovevidence at gmail.com
Sat Nov 1 10:04:35 EDT 2008


On Nov 1, 8:13 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> 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(...)
>
[snip]

> 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?

Just delete the names after instantiating the class:

del _Load
del _Run

I'm not trying to be snarky, sometimes the straightforward way is the
best.

I like Peter Otten's class decorator solution to this also, and
disagree that such complexity is necessarily unPythonic.  If you do it
a lot the complexity could result in an overall simplification.  It's
not something you want to casually throw at users, though.

A way to do this in 2.5 and below is to use a class hook (using
__metaclass__ attribute):

def self_instantiate(name,bases,clsdict):
    cls = type.__new__(type,name+"_type",
                       bases,clsdict)
    obj = cls()
    return obj

class load(Action):
    __metaclass__ = self_instantiate
    ....



Carl Banks



More information about the Python-list mailing list