[Python-ideas] Before and after the colon in funciton defs.

Steven D'Aprano steve at pearwood.info
Thu Sep 22 19:41:29 CEST 2011


Devin Jeanpierre wrote:
>> Decorators could be a good way to do this, but the problem in these
>> cases, is the function object doesn't have the needed support to make
>> things like this easy.
>>
>>
>> Probably the easiest and most direct way, would to be to add a new
>> keyword 'static' as MRAB suggested, but have it be an expression instead
>> of a command.
> 
> I hope I'm not bikeshedding here, but I much prefer decorators because
> they let you do more than just micro-optimization. They were mentioned
> before, in another thread, and I find them attractive.
> 
> A decorator basically lets you inject locals into already-existing
> functions. So if you want to, e.g., test a function that uses a global
> "urlopen" function to download a file, by replacing urlopen.


I find this idea extremely exciting. But have I missed something? Does 
this inject function actually exist somewhere? If I recall correctly, 
I've seen a bytecode hack or two that seemed to work, but I didn't think 
that was officially supported.


Comparing syntax:


def func(a, b):
     static f, g, h
     f = ...
     g = ...
     h = ...
     return f(g(h(a+b)))



@inject(
     f = ...
     g = ...
     h = ...)
def func(a, b):
     return f(g(h(a+b)))



or even:

def func(a, b):
     return f(g(h(a+b)))

another_func = @inject(
     f = ...
     g = ...
     h = ...)(func)



As far as syntax goes, I think both variants look good, but a decorator 
has two major advantages:

* you aren't limited to using it at function definition time, you can 
apply it after the event

* it doesn't need to be a keyword, or even a built-in: it could go into 
functools



-- 
Steven




More information about the Python-ideas mailing list