[Python-ideas] Multiple arguments for decorators

Chris Angelico rosuav at gmail.com
Mon Nov 30 22:32:13 EST 2015


On Tue, Dec 1, 2015 at 2:16 PM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> I'm having trouble interpreting the function name "call", though.  Am
> I missing something obvious ("Angelico" doesn't sound Dutch to me,
> though :-), or maybe there's a better (longer) name for it?
>
> Also, can call be expected to DTRT for anything *but* property?

No, it's not Dutch... but my maternal grandparents were Dutch, if that
helps? (My parents were both born here in Australia, but my
grandparents are split two-and-two Dutch and Sicilian. So I get to eat
garlic like nobody's business, and then pretend to understand Python.
Maybe.)

The semantics of the function I've given are simple: Pass it a
callable and a block of assignments (implemented as a class body), and
it calls the callable with the assignments as keyword arguments.

So it'll work for anything that accepts keyword arguments - which in
Python is nearly anything. It doesn't necessarily have to carry
callables:

import json
@call(json.loads)
class config:
    with open("config.json") as _f: # Leading underscore for non-arguments
        s = _f.read()
    encoding = "UTF-8"
    def object_hook(d):
        if "imag" in d and "real" in d and len(d)==2:
            return complex(d["real"], d["imag"])
        return d
    parse_int = float

import pprint
pprint.pprint(config)

Incidentally, this works in Python 2 as well as Python 3. I found out
by typoing the command and seeing a bunch of u'...' strings in the
pprint output - no other difference.

ChrisA


More information about the Python-ideas mailing list