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

Carl Matthew Johnson cmjohnson.mailinglist at gmail.com
Fri Sep 23 06:34:15 CEST 2011

Instead of a $ decorator, you could let decorators have a __prepare__ method that returns a dict to use for locals, as metaclasses do today.

I did a quick test in Python 3.2:

>>> @print("1")
... def f(x=print("2")): pass
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'NoneType' object is not callable

This shows that decorators are executed before the function is built. 

Since we're looking up the decorator before the function object has been created anyway, it wouldn't be impossible for the locals dictionary of the function to be "modified" before it's created, as we can do with metaclasses. If we did this, inject would look something like this:

class inject:
    def __init__(self, **kwargs):
        self.kwargs = kwargs
    def __prepare__(self):
        return self.kwargs
    def __call__(self, f):
        return f

And of course, there could be other applications for the __prepare__, such as using OrderedDict or whatever. (Not sure if we'd want to encourage that though…)

More information about the Python-ideas mailing list