Dynamically create a web worker with a `src` Python file, a unique `name` and optional `config` (dict or JSON string) and `type` (`py` for Pyodide or `mpy` for MicroPython, the default is `py`). This function creates a new web worker by injecting a ` ` tag into the docum
(src, name, config=None, type="py")
| 132 | |
| 133 | |
| 134 | async def create_named_worker(src, name, config=None, type="py"): |
| 135 | """ |
| 136 | Dynamically create a web worker with a `src` Python file, a unique |
| 137 | `name` and optional `config` (dict or JSON string) and `type` (`py` |
| 138 | for Pyodide or `mpy` for MicroPython, the default is `py`). |
| 139 | |
| 140 | This function creates a new web worker by injecting a `<script>` tag into |
| 141 | the document. The worker will be accessible via the `workers` proxy once |
| 142 | it's ready. |
| 143 | |
| 144 | It returns a promise that resolves to the worker reference when ready. |
| 145 | |
| 146 | ```python |
| 147 | from pyscript import create_named_worker |
| 148 | |
| 149 | |
| 150 | # Create a Pyodide worker. |
| 151 | worker = await create_named_worker( |
| 152 | src="./my_worker.py", |
| 153 | name="background-worker" |
| 154 | ) |
| 155 | |
| 156 | # Use the worker. |
| 157 | result = await worker.process_data() |
| 158 | |
| 159 | # Create with standard PyScript configuration. |
| 160 | worker = await create_named_worker( |
| 161 | src="./processor.py", |
| 162 | name="data-processor", |
| 163 | config={"packages": ["numpy", "pandas"]} |
| 164 | ) |
| 165 | |
| 166 | # Use MicroPython instead. |
| 167 | worker = await create_named_worker( |
| 168 | src="./lightweight_worker.py", |
| 169 | name="micro-worker", |
| 170 | type="mpy" |
| 171 | ) |
| 172 | ``` |
| 173 | |
| 174 | !!! info |
| 175 | |
| 176 | **The worker script should define** `__export__` to specify which |
| 177 | functions or objects are accessible from the main thread. |
| 178 | """ |
| 179 | # Create script element for the worker. |
| 180 | script = js.document.createElement("script") |
| 181 | script.type = type |
| 182 | script.src = src |
| 183 | # Mark as a worker with a name. |
| 184 | script.setAttribute("worker", "") |
| 185 | script.setAttribute("name", name) |
| 186 | # Add configuration if provided. |
| 187 | if config: |
| 188 | if isinstance(config, str): |
| 189 | config_str = config |
| 190 | else: |
| 191 | config_str = json.dumps(config) |