Can global variable be passed into Python function?

Marko Rauhamaa marko at pacujo.net
Fri Feb 28 14:20:52 EST 2014


Chris Angelico <rosuav at gmail.com>:

> On Sat, Mar 1, 2014 at 5:53 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
>> A dict dispatch table is just awful.
>
> Really? How is that? I've used them, often. Yes, there are times when
> I could express something more cleanly with a C-style switch
> statement, but other times the dispatch table is fundamentally
> cleaner. I shared an example a few posts ago in this thread; care to
> elaborate on how it's "just awful"?

Your example:

    compare_key = {
        # Same target(s).
        ast.Assign: lambda node: ' '.join(dump(t) for t in node.targets),
        # Same target and same operator.
        ast.AugAssign: lambda node: dump(node.target) + dump(node.op) + "=",
        # A return statement is always compatible with another.
        ast.Return: lambda node: "(easy)",
        # Calling these never compatible is wrong. Calling them
        # always compatible will give lots of false positives.
        ast.Expr: lambda node: "(maybe)",
        # These ones are never compatible, so return some
        # object that's never equal to anything.
        ast.Import: lambda node: float("nan"),
        ast.ImportFrom: lambda node: float("nan"),
        ast.Pass: lambda node: float("nan"),
        ast.Raise: lambda node: float("nan"),
        ast.If: lambda node: float("nan"),
    }

vs (my proposal):

    with key from ast:
        if Assign:
            return ' '.join(dump(t) for t in node.targets)
        elif AugAssign:
            # Same target and same operator.
            return dump(node.target) + dump(node.op) + "="
        elif Return:
            # A return statement is always compatible with another.
            return "(easy)"
        elif Expr:
            # Calling these never compatible is wrong. Calling them
            # always compatible will give lots of false positives.
            return "(maybe)"
        else:
            # These ones are never compatible, so return some
            # object that's never equal to anything.
            return float("nan")

Which do *you* find more readable?


Marko



More information about the Python-list mailing list