I have mine as a Saved Search, but you can also do it ad hoc
There is code there that defines the function, but I don't know Python so I never created any
I guess you can create your own function
The Calibre Users' Manual is one of the best I've seen in a long time:
https://manual.calibre-ebook.com/function_mode.html