[python-uk] Advice on decorator grammar

Stestagg stestagg at gmail.com
Wed Apr 3 13:43:43 CEST 2013


This seems redundant to me, the MyDecorator instance would not be bound to
anything, so you'll 'loose' the reference to it, except through the call to
decorator_method().

You could do this by making decorator_method a classmethod:

class MyDecorator(object):

    @classmethod
    def decorate_this(cls, ...):
        pass

allowing you to use it:

@MyDecorator.decorate_this(foo)

If your intent is to pass arguments to the MyDecorator instance, just pass
them to the decorator method directly.

Finally, if you're trying to implement singleton like behaviour.  (a
registry etc..) then using your example of binding an instance of
MyDecorator() to a module-level name is sensible.

MY_REGISTRY = MyDecorator()

@MY_REGISTRY.decoate_this()
def wrapped():
    ...

Does your use-case match any of these?

Thanks

Steve


On Wed, Apr 3, 2013 at 12:34 PM, Simon Yarde <simonyarde at me.com> wrote:

> Hi All
>
> I've not posted to this list before. Hello!
>
> I have a question about decorators and have failed to devise a search that
> has thrown up any history of discussion on this particular matter.
>
> Does the following seem like something that 'should' work? Or is anyone
> aware of a source of documentation that explains historically why the
> following syntax might not be allowed?
>
> I hope this sort of conundrum/discussion-point is appropriate to this
> forum; I'm not on python-dev and this is obviously not a bug.
>
> So..
>
> Decorator grammar is this:
>
> decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
>
> The grammar prevents this:
>
> >>> class MyDecorator:
> ...     def decorator_method():
> ...             pass
> ...
> >>> @MyDecorator().decorator_method()
>   File "<stdin>", line 1
>     @MyDecorator().decorator_method()
>                   ^
> SyntaxError: invalid syntax
>
> But is possible to achieve the desired effect by assigning the class
> instance to variable:
>
> >>> mydecorator = MyDecorator()
> ... @mydecorator.decorator_method
> ... def f():
>
>
> My initial thoughts were that the syntax provided a neat way to provide a
> configurable decorator class instance with a number of alternative
> decorator-function generating methods, rather than just the usual __call__.
>
> S
> _______________________________________________
> python-uk mailing list
> python-uk at python.org
> http://mail.python.org/mailman/listinfo/python-uk
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-uk/attachments/20130403/3a1ef3e7/attachment.html>


More information about the python-uk mailing list