Simplifying anonymous inner classes?

Duncan Booth duncan.booth at invalid.invalid
Mon Nov 3 04:08:10 EST 2008


Tim Chase <python.list at tim.thechases.com> wrote:

>    def __init__(self, ...):
>      self.parser = optparse.OptionParser(...)
>    def __call__(self, argv): # argv is a list like sys.argv
>      options, args = self.parser.parse_args(argv)
>      # do something with options/args
> 
> So that background provided, the original question was more about 
> how to create anonymous sub-classes with overridden methods so my 
> Backend objects' code & namespaces weren't littered with objects 
> that were only defined to be instantiated once in exactly the 
> location they were defined.
> 

I think Martin v. Löwis expanded sufficiently on the idea of using 
decorators, so I'll just point out one problem you may run into: the 
pseudo-code you posted will create callable attributes on the class, but 
unless you also implement the descriptor protocol they won't act like 
methods. i.e. you won't get any reference to the instance on which you 
called load/run/frob or whatever.

Of course the decorator solution has the opposite problem: you get a 
reference to your Backend instance but not to the decorated function 
itself. That probably shouldn't matter: what you wrote above looks to me 
like you just do:

class DatabaseBackend:
    @Action(...)
    def load(self, options, args):
    	   ...

and the parse_args call is something done in the decorator rather than 
repeated in each and every method that follows this pattern. Or even 
better make the options parse to specific keyword arguments so you can 
test an option directly inside the method rather than having to look it 
up in a dictionary.

class DatabaseBackend:
    @Action("load a thang into memory").
       add_option("-f", "--file", help="load from file",
                  default=None).
       add_option("--frobnify", help="frobnify the thang",
                 default=False, action="store_true")
    def load(self, file, frobnify, args):
       ...

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list