Skip to content

Commit f387f6d

Browse files
committed
regex based python minification
1 parent 459bcc5 commit f387f6d

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

src/reactpy/pyscript/utils.py

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import functools
55
import json
6+
import re
67
import shutil
78
import subprocess
89
import textwrap
@@ -22,14 +23,29 @@
2223
if TYPE_CHECKING:
2324
from collections.abc import Sequence
2425

26+
_logger = getLogger(__name__)
27+
28+
29+
def minify_python(source: str):
30+
"""Minify Python source code."""
31+
# Remove comments
32+
source = re.sub(r"#.*\n", "\n", source)
33+
# Remove docstrings
34+
source = re.sub(r'""".*?"""', "", source, flags=re.DOTALL)
35+
# Remove extra newlines
36+
source = re.sub(r"\n+", "\n", source)
37+
# Remove empty lines
38+
source = re.sub(r"\s+\n", "\n", source)
39+
# Remove leading and trailing whitespace
40+
return source.strip()
2541

26-
PYSCRIPT_COMPONENT_TEMPLATE = (
27-
Path(__file__).parent / "component_template.py"
28-
).read_text(encoding="utf-8")
29-
PYSCRIPT_LAYOUT_HANDLER = (Path(__file__).parent / "layout_handler.py").read_text(
30-
encoding="utf-8"
42+
43+
PYSCRIPT_COMPONENT_TEMPLATE = minify_python(
44+
(Path(__file__).parent / "component_template.py").read_text(encoding="utf-8")
45+
)
46+
PYSCRIPT_LAYOUT_HANDLER = minify_python(
47+
(Path(__file__).parent / "layout_handler.py").read_text(encoding="utf-8")
3148
)
32-
_logger = getLogger(__name__)
3349

3450

3551
def render_pyscript_executor(file_paths: tuple[str, ...], uuid: str, root: str) -> str:
@@ -206,5 +222,6 @@ def reactpy_version_string() -> str: # pragma: no cover
206222

207223

208224
@functools.cache
209-
def cached_file_read(file_path: str) -> str:
210-
return Path(file_path).read_text(encoding="utf-8").strip()
225+
def cached_file_read(file_path: str, minifiy=True) -> str:
226+
content = Path(file_path).read_text(encoding="utf-8").strip()
227+
return minify_python(content) if minifiy else content

0 commit comments

Comments
 (0)