Skip to content

Commit a290f27

Browse files
authored
fix(loader): Add loaded module to sys.modules to help libraries using data from annotation scopes
PR-12: #12
1 parent d397629 commit a290f27

File tree

5 files changed

+22
-1
lines changed

5 files changed

+22
-1
lines changed

src/copier_templates_extensions/extensions/loader.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import sys
56
from importlib.util import module_from_spec, spec_from_file_location
67
from pathlib import Path
78
from typing import TYPE_CHECKING, Any
@@ -80,9 +81,10 @@ def _import_template_module(self, relative_path: str | Path) -> ModuleType:
8081
"Please report this issue to the template maintainers.",
8182
)
8283
spec = spec_from_file_location(
83-
f"copier_templates_extensions.{module_name}",
84+
module_full_name := f"copier_templates_extensions.{module_name}",
8485
template_relative_path,
8586
)
8687
module = module_from_spec(spec) # type: ignore[arg-type]
88+
sys.modules[module_full_name] = module
8789
spec.loader.exec_module(module) # type: ignore[union-attr]
8890
return module
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
_subdirectory: template
2+
_jinja_extensions:
3+
- copier_templates_extensions.TemplateExtensionLoader
4+
- extensions/ctx.py:Success
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from __future__ import annotations
2+
from dataclasses import dataclass
3+
from jinja2.ext import Extension
4+
5+
@dataclass
6+
class Test:
7+
key: str
8+
value: str
9+
10+
class Success(Extension):
11+
def __init__(self, environment):
12+
super().__init__(environment)
13+
environment.globals.update(success=True)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Success variable: {{ success|default("not set") }}

tests/test_extensions.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
("modifying_context", "True"),
1919
("not_updating_context_for_prompts", "True"),
2020
("loading_normal_extension", "not set"),
21+
("dataclass", "True"),
2122
],
2223
)
2324
def test_extensions(tmp_path: Path, template_name: str, expected: str) -> None:

0 commit comments

Comments
 (0)