Statespressions? (Re: Draft Pep (was: Re: Let's Talk About Lambda Functions!))

Jonathan Hogg jonathan at onegoodidea.com
Wed Aug 7 09:29:01 CEST 2002


On 7/8/2002 4:47, in article 3D509834.8050800 at something.invalid, "Greg
Ewing" <see_reply_address at something.invalid> wrote:

> It occurred to me while I was writing it that using a class
> would be almost as good. But not quite, for various reasons.
> First, you don't actually want a class, you want an instance
> of a class; either that or wrap all the functions in
> classmethod, which would be rather tedious and ugly.

Don't try this at home, but:

-----------------------------------------------------------------
def switch( name, bases, dict ):
    calldict = {}
    for f in dict.values():
        if hasattr( f, 'func_defaults' ) and f.func_defaults:
            calldict[f.func_defaults[0]] = f
    value = bases[0]
    if value in calldict:
        return calldict[bases[0]]()
    elif 'default' in dict:
        return dict['default']()
    else:
        raise KeyError( 'Unmatched switch' )
    

def test( x ):

    print 'Switching on x =', x

    class foo( x ):
        __metaclass__ = switch
        
        def a( case = 1 ):
            print 'It was a 1'
        
        def b( case = 5 ):
            print 'It was a 5'
            return 'Wahay!'
    
        def c( case = 7 ):
            print 'It was a 7'
            
        def default():
            print 'Who knows?'
            
    print 'Result was:', foo


test( 5 )
-----------------------------------------------------------------

It's just possible that this is the worst example of a metaclass I've been
able to come up with so far ;-)

[Of course it'd be better if the methods were anonymous ;-)]

Jonathan




More information about the Python-list mailing list