[Python-ideas] parameter annotation semantics
Chris Rebert
pyideas at rebertia.com
Sun Apr 17 08:36:34 CEST 2011
On Sat, Apr 16, 2011 at 9:53 PM, Bruce Leban <bruce at leapyear.org> wrote:
> Subject was: Re: [Python-ideas] Simple class initialization
> On Sat, Apr 16, 2011 at 6:27 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> Bruce Leban wrote:
>>> One
>>> of the strange aspects (to me) of parameter annotations is that they have
>>> no
>>> semantics which opens them up to multiple conflicting uses.
>>
>> That's not a bug, that's a feature.
>>
>> It's been stated many times by Guido that it's far too early to
>> standardize on a single meaning for annotations. (We may *never* standardize
>> on a single meaning.) Instead, it is up to the library or decorator to
>> impose whatever meaning makes sense for that particular library or
>> decorator.
>
> I understand that. I can still think it a bit strange, can't I? To be more
> specific, you hit the crux of the problem with the statement "it is up to
> THE library or decorator to impose whatever meaning makes sense" [emphasis
> added] is that it assumes the singular. If I want to use two decorators
> which impose different meanings, I'm stuck. Imagine I have two decorators
I imagine one nice way to approach the problem would be a
meta-decorator like the following:
[completely untested; please excuse likely Gmail line-wrapping]
NULL = object()
def annotation_sensitively_decorate(*decs):
def decorate(f):
annots = f.func_annotations
keys = list(annots.keys())
for dec, assignments in zip(decs, zip(*list(annots.values()))):
# determine and swap in annotations for current decorator
cur_annots = {k:v for k,v in zip(keys, assignments) if v
is not NULL}
f.func_annotations = cur_annots
f = dec(f)
f.func_annotations = annots # restore orig annotations
return f
return decorate
@annotation_sensitively_decorate(log_me, memoize)
def c(foo: [do_log, memo_value(int)], bar: [no_log,
memo_value(tuple)], baz: [NULL, NULL]) -> [NULL, NULL]:
...
Cheers,
Chris
--
Metaprogramming is the best kind of programming, except when debugging.
http://blog.rebertia.com
More information about the Python-ideas
mailing list