Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 83 additions & 29 deletions src/deigma/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,12 @@ def template(
source = load_template_source(path)

if source is not None:
return inline_template(source, serialize=serialize, use_proxy=use_proxy)
return inline_template(
source,
serialize=serialize,
use_proxy=use_proxy,
_path=str(path) if path else None,
)

raise ValueError("Invalid arguments")

Expand All @@ -87,33 +92,33 @@ def inline_template(
*,
serialize: Serialize = DEFAULT_SERIALIZE,
use_proxy: bool = USE_PROXY,
_path: str | None = None,
) -> Callable[[type[T]], type[Template]]:
def decorator(cls: type[T]) -> type[T]:
config = ConfigDict(arbitrary_types_allowed=True)
cls = pydantic_dataclass(init=False, config=config)(
type(cls.__name__, (cls,), dict(cls.__dict__))
)
cls.__is_deigma_template__ = True
cls._source = cleandoc(source)

_src = cleandoc(source)
engine = Jinja2Engine(serialize=serialize)
cls._engine = engine
cls._variables = engine.introspect_variables(source)
variables = tuple(engine.introspect_variables(_src))

static_fields = set(cls.__annotations__)
properties = {
prop for prop in vars(cls) if isinstance(getattr(cls, prop), property)
}
fields = static_fields | properties

if not set(cls._variables).issubset(fields):
variables = cls._variables
if not set(variables).issubset(fields):
msg = (
"Template variables mismatch. Template fields must match variables in source:\n\n"
f"fields on type: {fields}, variables in source: {variables}"
)

if any(source.endswith(ext) for ext in COMMON_JINJA2_EXTENSIONS):
extension = source.split(".")[-1]
if any(_src.endswith(ext) for ext in COMMON_JINJA2_EXTENSIONS):
extension = _src.split(".")[-1]
msg += (
f"\n\nHint: 'source' ends with '.{extension}', "
"which is a common Jinja2 extension. "
Expand All @@ -123,39 +128,88 @@ def decorator(cls: type[T]) -> type[T]:

raise ValueError(msg)

cls._compiled_template = engine.compile_template(cls._source)
cls._type_adapter = TypeAdapter(cls)
def _get_adapter(c):
ta = getattr(c, "_type_adapter", None)
if ta is None:
ta = TypeAdapter(c)
setattr(c, "_type_adapter", ta)
return ta

if use_proxy:

def __str__(instance):
proxied = {
field: getattr(instance._proxy, field) for field in cls._variables
def __str__(
instance,
_cache={
"tmpl": None,
"engine": Jinja2Engine(serialize=serialize),
"src": _src,
"vars": variables,
"path": _path,
"mtime": None,
},
):
# Optional file mtime check for hot-reload
if _cache["path"] and os.path.exists(_cache["path"]):
mtime = os.path.getmtime(_cache["path"])
if _cache["mtime"] != mtime:
_cache["src"] = load_template_source(_cache["path"])
_cache["tmpl"] = None # force recompile
_cache["mtime"] = mtime

if _cache["tmpl"] is None:
_cache["tmpl"] = _cache["engine"].compile_template(_cache["src"])

if not hasattr(instance, "_proxy"):
adapter = _get_adapter(instance.__class__)
instance._proxy = SerializationProxy.build(instance, adapter)

proxied = {name: getattr(instance._proxy, name) for name in _cache["vars"]}
return _cache["tmpl"].render(proxied)

else:

def __str__(
instance,
_cache={
"tmpl": None,
"engine": Jinja2Engine(serialize=serialize),
"src": _src,
"vars": variables,
"path": _path,
"mtime": None,
},
):
# Optional file mtime check for hot-reload
if _cache["path"] and os.path.exists(_cache["path"]):
mtime = os.path.getmtime(_cache["path"])
if _cache["mtime"] != mtime:
_cache["src"] = load_template_source(_cache["path"])
_cache["tmpl"] = None # force recompile
_cache["mtime"] = mtime

if _cache["tmpl"] is None:
_cache["tmpl"] = _cache["engine"].compile_template(_cache["src"])

adapter = _get_adapter(instance.__class__)
serialized = adapter.dump_python(instance)
rendered_fields = {
name: _render_field_maybe(getattr(instance, name), serialized[name])
for name in _cache["vars"]
}
return instance._compiled_template.render(proxied)
return _cache["tmpl"].render(rendered_fields)

Comment on lines 129 to +195
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is significant code duplication between the __str__ method defined when use_proxy is True and when it is False. The logic for hot-reloading based on file modification time and for lazy template compilation is identical in both branches.

This duplication makes the code harder to maintain, as any changes to this logic would need to be applied in two places. To improve this, you could extract the duplicated logic into a shared helper function within the decorator scope. This function would handle checking for file modifications and compiling the template, and could be called from both __str__ implementations.

For example:

def _get_compiled_template(cache):
    # Optional file mtime check for hot-reload
    if cache["path"] and os.path.exists(cache["path"]):
        mtime = os.path.getmtime(cache["path"])
        if cache["mtime"] != mtime:
            cache["src"] = load_template_source(cache["path"])
            cache["tmpl"] = None  # force recompile
            cache["mtime"] = mtime

    if cache["tmpl"] is None:
        cache["tmpl"] = cache["engine"].compile_template(cache["src"])
    return cache["tmpl"]

# ... then in both __str__ implementations:
tmpl = _get_compiled_template(_cache)
# ... rest of the logic

cls.__str__ = __str__

if use_proxy:
original_init = cls.__init__

def __init__(instance, *args, **kwargs):
original_init(instance, *args, **kwargs)
instance._proxy = SerializationProxy.build(instance, cls._type_adapter)
adapter = _get_adapter(cls)
instance._proxy = SerializationProxy.build(instance, adapter)

cls.__init__ = __init__

else:

def __str__(instance):
serialized = cls._type_adapter.dump_python(instance)
rendered_fields = {
field: _render_field_maybe(
getattr(instance, field), serialized[field]
)
for field in cls._variables
}
return instance._compiled_template.render(rendered_fields)

cls.__str__ = __str__

return cls

return decorator
Expand Down
Loading