Macro as decorators

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Macro as decorators

Ford O.
Is it possible to write macro that will work as python decorator?
Reply | Threaded
Open this post in threaded view
|

Re: Macro as decorators

Kevin Squire
Possibly.

Do you have a specific example in mind?  That will probably get you a less ambivalent answer. :-)

Cheers,
   Kevin 

On Monday, May 9, 2016, Ford Ox <[hidden email]> wrote:
Is it possible to write macro that will work as python decorator?
Reply | Threaded
Open this post in threaded view
|

Re: Macro as decorators

Andras Niedermayer
In reply to this post by Ford O.
It's possible to have a macro in Julia that emulates Python decorators. But it's a separate question whether you really want to do it, there might be more efficient/elegant ways to achieve the same in Julia for a specific use case.

Here's a macro that emulates Python decorators and an example how to use it:

julia> macro decorator(dec, func)
         name
= func.args[1].args[1]
         hiddenname
= gensym()
         func
.args[1].args[1] = hiddenname
         quote
           $func
           
const $(esc(name)) = $dec($hiddenname)
         
end
       
end
julia
> foo(f) = x->2*f(x+10)
julia
> @decorator foo function bar(x)
         
return x+1
       
end
julia
> bar(0)
22

This is the same as in Python
In [2]: def foo(f):
   
...:     return lambda x: 2*f(x+10)
   
...:


In [3]: @foo
   
...: def bar(x):
   
...:     return x+1
   
...:


In [4]: bar(0)
Out[4]: 22

Of course, one can also use this for something useful :-), like:
julia> logger(f) = x-> (println("input: $x"); result = f(x); println("output: $result"); result)
logger
(generic function with 1 method)


julia
> @decorator logger baz(x)=x+1
(anonymous function)


julia
> baz(3)
input
: 3
output
: 4
4




On Monday, May 9, 2016 at 3:42:22 PM UTC+2, Ford Ox wrote:
Is it possible to write macro that will work as python decorator?