|
4 | 4 | from typing import Any, Callable, Sequence |
5 | 5 |
|
6 | 6 |
|
7 | | -def dynamic_import( |
| 7 | +def setup_java_imports( |
8 | 8 | module_name: str, |
9 | 9 | module_file: str, |
10 | 10 | endpoints: Sequence[str] = (), |
11 | 11 | base_prefix: str = "", |
12 | 12 | ) -> tuple[list[str], Callable[[str], Any]]: |
| 13 | + """Setup a module to dynamically import Java class names. |
| 14 | +
|
| 15 | + This function creates a `__getattr__` function that, when called, will dynamically |
| 16 | + import the requested class from the Java namespace corresponding to this module. |
| 17 | +
|
| 18 | + :param module_name: The dotted name/identifier of the module that is calling this |
| 19 | + function (usually `__name__` in the calling module). |
| 20 | + :param module_file: The path to the module file (usually `__file__` in the calling |
| 21 | + module). |
| 22 | + :param endpoints: A list of Java endpoints to add to the scyjava configuration. |
| 23 | + :param base_prefix: The base prefix for the Java package name. This is used when |
| 24 | + determining the Java class path for the requested class. The java class path |
| 25 | + will be truncated to only the part including the base_prefix and after. This |
| 26 | + makes it possible to embed a module in a subpackage (like `scyjava.types`) and |
| 27 | + still have the correct Java class path. |
| 28 | + :return: A 2-tuple containing: |
| 29 | + - A list of all classes in the module (as defined in the stub file), to be |
| 30 | + assigned to `__all__`. |
| 31 | + - A callable that takes a class name and returns a proxy for the Java class. |
| 32 | + This callable should be assigned to `__getattr__` in the calling module. |
| 33 | + The proxy object, when called, will start the JVM, import the Java class, |
| 34 | + and return an instance of the class. The JVM will *only* be started when |
| 35 | + the object is called. |
| 36 | +
|
| 37 | + Example: |
| 38 | + If the module calling this function is named `scyjava.types.org.scijava.parsington`, |
| 39 | + then it should invoke this function as: |
| 40 | +
|
| 41 | + .. code-block:: python |
| 42 | +
|
| 43 | + from scyjava._stubs import setup_java_imports |
| 44 | +
|
| 45 | + __all__, __getattr__ = setup_java_imports( |
| 46 | + __name__, |
| 47 | + __file__, |
| 48 | + endpoints=["org.scijava:parsington:3.1.0"], |
| 49 | + base_prefix="org" |
| 50 | + ) |
| 51 | + """ |
13 | 52 | import scyjava |
14 | 53 | import scyjava.config |
15 | 54 |
|
|
0 commit comments