I recently had a discussion with a fellow perlmonger about a 3h video¹ about meta-programming in Python thanks to so called decorators. (something like advice in LISP)
So my reply was
Great, but what exactly are the benefits over attributes and type-glob manipulation in Perl?
His long reply can be summarized with something like
So I accepted the challenge to prove him wrong:
Taking this (rather stupid) example from SO:
def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello world" print hello() ## returns <b><i>hello world</i></b>
I hacked this code
use strict; use warnings; use Data::Dumper qw'Dumper'; use Attribute::Handlers; use feature 'say'; sub wrap { my ($glob,$c_wrapper) = @_; no warnings 'redefine'; *$glob = $c_wrapper; } sub BOLD :ATTR { my ($pkg,$glob,$ref) = @_; wrap $glob => sub { "<b>" . $ref->() . "</b>" }; } sub ITALIC :ATTR { my ($pkg,$glob,$ref) = @_; wrap $glob => sub { "<i>" . $ref->() . "</i>"}; } sub hello :ITALIC :BOLD { return "hello world"; } say hello(); __END__ <b><i>hello World</i></b>
IMHO the Perl code is already better readable and can even be further improved with more syntactic sugar.
Not every decorator really needs to wrap code, abstracting it into a function wrap from an imported module seems reasonable (Python-folks always return the identical function-ref to handle this)
My friend was impressed, but maybe he wasn't critical enough.
Here my questions :
Actually I wanted to meditate more about the issue and refine the code before posting, but I'm quite busy at the moment and the risk to forget this task in a drawer is quite high.
So following the release often paradigm I just posted my raw results...
At least I hope you have now good arguments, if someone claims Python was superior because of decorators!
Cheers Rolf
( addicted to the Perl Programming Language)
¹) OMG 8-|
|
|---|