Skip to content

Commit 7eedc62

Browse files
committed
add dynamic module importing
allows to add modules without recompiling the program
1 parent 46d3dee commit 7eedc62

File tree

4 files changed

+28
-2
lines changed

4 files changed

+28
-2
lines changed

README.md

+11-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,17 @@ To do Python development for the visualizer, it's recommended to create its Pyth
4747
opal pycompile SortingVisualizer.opal
4848
```
4949

50-
And then add these lines on top of your Python code:
50+
When adding modules to the visualizer dynamically (through the `external` folder), you can use the pycompiled version like this:
51+
```py
52+
from typing import TYPE_CHECKING
53+
54+
if TYPE_CHECKING:
55+
from SortingVisualizer import *
56+
```
57+
58+
This way, your IDE will be able to typecheck the program and give you proper hints, while not executing the import when the code is actually ran.
59+
60+
Instead, if you are writing code that will be embedded in the compiled visualizer, add these lines on top of your Python code:
5161
```py
5262
#opal$if False
5363
from SortingVisualizer import *

SortingVisualizer.opal

+15-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ new float UNIT_SAMPLE_DURATION = 1.0 / 30.0,
1717
N_OVER_R = NATIVE_FRAMERATE / RENDER_FRAMERATE,
1818
R_OVER_N = RENDER_FRAMERATE / NATIVE_FRAMERATE;
1919

20-
new str VERSION = "2024.6.29";
20+
new str VERSION = "2024.7.19";
2121

2222
import math, random, time, os, numpy, sys,
2323
pygame_gui, json, subprocess, shutil,
@@ -2138,5 +2138,19 @@ main {
21382138
$includeDirectory os.path.join(HOME_DIR, "shuffles")
21392139
$includeDirectory os.path.join(HOME_DIR, "sorts")
21402140

2141+
try {
2142+
new dynamic externalMods = os.path.join(HOME_DIR, "external");
2143+
for module in os.listdir(externalMods) {
2144+
if module.endswith(".py") {
2145+
with open(os.path.join(externalMods, module), "r", encoding = "utf-8") as f {
2146+
use f; exec(f.read());
2147+
}
2148+
}
2149+
}
2150+
} catch Exception as e {
2151+
IO.out("An error occurred while importing external modules. Exception:\n{formatException(e)}");
2152+
sys.exit(1);
2153+
}
2154+
21412155
sortingVisualizer.run();
21422156
}

build.iproj

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
source: "SortingVisualizer.opal",
22
copy: {
33
"resources": folder,
4+
"external": folder,
45
"profiles": folder,
56
"threads": folder,
67
"config": folder

external/readme.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
put external modules to be dynamically loaded inside the visualizer here!

0 commit comments

Comments
 (0)