Decorator to add key parameter support to an existing sort function
Python is open-source, and all the source code in the GitHub repository python/cpython. For a great deal of the built-ins, they can be found in cpython/Python/bltinmodule.c
. In the current revision, the beginning of the sorted function definitions is found at line 2175, and the actual function itself is found at line 2201.

However, I'm not sure that knowing the implementation of sorted can help you too much with optimizing heapsort, because sorted uses Timsort.

I can make a suggestion: decorators will always add overhead, and particularly in a case like this, it's probably better to just make a new version of the function that integrates the key parameter with the original function, though this answer might miss the entire point of your question.