Simplifying anonymous inner classes?

"Martin v. Löwis" martin at v.loewis.de
Sat Nov 1 11:25:00 EDT 2008


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

I agree with Carl Banks that what you do is already fairly Pythonic:
explicit is better than implicit, and simple is better than complex.
What you do *is* simple, and easy to read - no magic involved.
You wish it to be more concise - but I think that would make *less*
pythonic, not more.

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

I agree with Duncan Booth that what you want to implement through
objects is perhaps already available in methods. For example,
you might use function decorators to create the option definitions.

So you could write

class DatabaseBackend:
    @Action("load a thang into memory").
       add_option("-f", "--file", help="load from file").
       add_option(...)
    def load(self, args):
       ...

Notice that the name of the command can be reflected from the
method's __name__, so I don't need to pass it into the Action
constructor. To implement the decorator, I suggest to just set
a function attribute, and return the original function.

HTH,
Martin



More information about the Python-list mailing list