View Single Post
Old 10-11-2022, 12:48 PM   #45
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
Quote:
Originally Posted by un_pogaz View Post
However, not sure if passing the named argument as an attribute is the best. I'd see more of a ctx.kwargs attribute to being able to process it as you wants.
Beyond the minor risk of collision in the future, using attributes means using getattr(ctx, 'name', default) which seems less elegant than ctx.kwargs as a dict, which can be used in a more dynamic way.
Unless it is usual in python to pass kwargs arguments as attributes for a class.
The idea is to make it easy for the person writing a template. It is definitely easier to write and understand ctx.something than ctx.kwargs['something ']. Also, it isn't obvious what **kwargs means even to seasoned programmers.

I defined PythonTemplateContext the way I did because I am worried that someone might define a context outside of base calibre (where I can't see it). I don't know why someone would do that, but it is possible. That is why PythonTemplateContext.__init__() uses **kwargs. If and when we add items to the context we pass them to PythonTemplateContext.__init__() as named parameters that are converted to attributes by __init__. This way adding new attributes to the context object won't break the plugin code because __init__'s signature doesn't change. Of course the new attributes won't be there, but that might be OK for the plugin.

I put in ctx.attributes() so someone could 'inspect' what attributes are in the context object.
chaley is offline   Reply With Quote