1

Prefer a micropython answer but will accept CPython

I'm implementing a Python function in C.

How do you apply a decorator to Python function written in C?

2
  • You should check out the answers to this question. Commented Jul 23, 2018 at 14:41
  • Wouldn't the function be exposed through the Python API? And then you can just apply the decorator at that level? Commented Jul 23, 2018 at 14:43

1 Answer 1

3

Decorators can be invoked with a function as their argument. So if you would have written this (in Python):

@mydeco
def myfunc(x, y):
    return x * y

You can instead write this:

def myimpl(x, y):
    return x * y

myfunc = mydeco(myimpl)

You can then move myimpl to C.

If your decorator takes arguments:

myfunc = mydeco(a, b)(myimpl)
Sign up to request clarification or add additional context in comments.

1 Comment

Suggest also demonstrating passing arguments to the decorator: @mydeco(1,2,3) def myfunc(...) -> myfunc = mydeco(1,2,3)(myimpl). Double function call parentheses are surprising the first several times you see them, and it's not obvious from the documentation that this is how you do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.