View Single Post
Old 10-11-2022, 11:48 AM   #41
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 12,476
Karma: 8025702
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
@kovid has accepted the changes. However, he made a good suggestion that I will implement, which changes the signature of the evaluate function. He suggests:
Code:
python:
def evaluate(book, ctx):
where 'ctx' has attributes (not dictionary keys) for all the other 'things' that can be passed, for example ctx.db. This is as extensible as **kwargs but is simpler to use and to understand.

The context object is an instance of class defined in calibre.utils.formatter, which I have currently defined as:
Code:
class PythonTemplateContext(object):

    def __init__(self, **kwargs):
        # Set attributes we already know must exist.
        self.db = None
        self.arguments = None
        self.globals = None

        # Create/set attributes from the named parameters. Doing it this way we
        # aren't required to change the signature of __init__ if we add
        # attributes in the future. However, if a user depends upon the existence
        # of some attribute and the context creator doesn't supply it then the
        # user will get an AttributeError exception.
        for k,v in kwargs.items():
            setattr(self, k, v)
I will document it in the comments that the template editor can paste into the template, and in the 'real' documentation.

EDIT: changes are in my repo and submitted to Kovid.

Last edited by chaley; 10-11-2022 at 12:18 PM.
chaley is offline   Reply With Quote