M
Modular8mo ago
Joel

Custom decorator

I am currently working on a custom mojo library, and i tried to implement a custom decorator so I could write less code. But while compilation an error ocurred, so I would like to ask: Is it possible to implement custom decorators in Mojo and if yes, what is the syntax for that ? Example Code (The code in my project is too long to mention here):
# defines a decorator extending a functions applicability from Integers to Vectors

# defines the decorator
fn extend_to_vec(func: fn(Int) capturing -> Int) -> fn(DynamicVector[Int]) capturing -> DynamicVector[Int]:
# defines the returned function
fn vecfunc(vec: DynamicVector[Int])-> DynamicVector[Int]:
# return vector
var val = DynamicVector[Int]()
# iterate over vector
for i in range(len(vec)):
# append result of Int function applied to the ith element of the vector
val.append(func(vec[i]))
return val

return vecfunc

# decorator applied to a function incrementing a value by one
@extend_to_vec
fn increment(i: Int) -> Int:
return i + 1

fn main():
# should produce an error, but doesn't
var i = 5
print(i)
i = increment(i)
print(i)

# shouldn't produce an error, but does
var vec = DynamicVector[Int]()
vec.append(1)
vec.append(2)
vec.append(3)
print(vec[0])
vec = increment(vec)
print(vec[0])
# defines a decorator extending a functions applicability from Integers to Vectors

# defines the decorator
fn extend_to_vec(func: fn(Int) capturing -> Int) -> fn(DynamicVector[Int]) capturing -> DynamicVector[Int]:
# defines the returned function
fn vecfunc(vec: DynamicVector[Int])-> DynamicVector[Int]:
# return vector
var val = DynamicVector[Int]()
# iterate over vector
for i in range(len(vec)):
# append result of Int function applied to the ith element of the vector
val.append(func(vec[i]))
return val

return vecfunc

# decorator applied to a function incrementing a value by one
@extend_to_vec
fn increment(i: Int) -> Int:
return i + 1

fn main():
# should produce an error, but doesn't
var i = 5
print(i)
i = increment(i)
print(i)

# shouldn't produce an error, but does
var vec = DynamicVector[Int]()
vec.append(1)
vec.append(2)
vec.append(3)
print(vec[0])
vec = increment(vec)
print(vec[0])
5 Replies
a2svior
a2svior8mo ago
I think custom decorators are currently not supported (from github issues) https://github.com/modularml/mojo/discussions/216#discussioncomment-5956295
GitHub
Create a new decorator · modularml mojo · Discussion #216
What's not working? # create my hello decorator fn my_hello_decorator(func): fn wrapper(): print("Hello,") func() print("Bye Bye!") return wrapper # use my hello decorator @...
Joel
Joel8mo ago
@a2svior Thank you!
a2svior
a2svior8mo ago
I'd like to see custom decorators myself though, let's upvote this issue
Joel
Joel8mo ago
Me too, lets do it.
ModularBot
ModularBot8mo ago
Congrats @Joel, you just advanced to level 2!
Want results from more Discord servers?
Add your server