Language mavens: Is there a programming with "if then else ENDIF" syntax?

Steve Howell showell30 at
Wed Nov 18 10:15:32 CET 2009

On the topic of "switch" statements and even-more-concise-then-we-have-
already if/elif/else/end constructs, I have to say that Python does
occasionally force you to write code like the code below.  Maybe
"force" is too strong a word, but Python lends itself to if/elif
blocks like below, which get the job done just fine, but which are not
syntactically pretty, due to the "(el){0,1}if kind ==" duplication.
There are often cases where if/elif statements are just a smell that
you do not know how to do dictionary lookups, but if you converted the
below code to use dictionary lookups, you would complicate the code
almost as much as you abstracted the code, if not more, unless I am
just being very naive.  Anonymous methods would help to a certain
degree.  I am not saying I want either anonymous methods or switch
statements, but the lack of either in a language leads to very
procedural looking code when you use number-of-lines-of-code as a
(possibly dubious) metric.

Maybe this excerpt can be golfed down to something simpler, I would
love to see it!

        if kind == 'dict':
            return dictionary_schema(ast)
        elif kind == 'list':
            method = dictionary_schema(ast)
            return lambda lst: map(method, lst)
        elif kind == 'attr':
            return ((lambda obj: getattr(obj, ast.field)), ast.field)
        elif kind == 'key':
            return (lambda obj: obj.get(ast.field), ast.field)
        elif kind == 'as':
            method, old_name = schema(ast.parent)
            return (method, ast.synonym)
        elif kind == 'call':
            method, old_name = schema(ast.parent)
            def call(obj):
                return method(obj)()
            return (call, old_name)
        elif kind == 'recurse':
            expr = ast.expr
            kind = expr.kind
            method, field_name = schema(ast.parent)
            if kind in ['attr', 'key']:
                new_method, new_field_name = schema(expr)
                field_name = new_field_name
            elif kind in ['dict', 'list']:
                new_method = schema(expr)
                raise Exception('unknown kind!')
            def recurse(obj):
                obj = method(obj)
                return new_method(obj)
            return (recurse, field_name)
            raise Exception('unknown kind!')

More information about the Python-list mailing list