mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-20 19:40:18 +00:00
commit 7e52f767ca130a49abb90ec922d74d2f5e9be078 Author: blueloveTH <blueloveTH@foxmail.com> Date: Sat Jun 1 12:49:46 2024 +0800 some optimize commit 3e2ad5b1fbad4367c80ea1325d1aa379282c10c4 Author: blueloveTH <blueloveTH@foxmail.com> Date: Sat Jun 1 12:29:53 2024 +0800 some fix commit bc0e530c72896a23cb6616ff4197ac36913389a4 Author: blueloveTH <blueloveTH@foxmail.com> Date: Sat Jun 1 00:00:47 2024 +0800 some fix commit f17ddcf8299c5d6803085cd3263181f44284f31b Author: blueloveTH <blueloveTH@foxmail.com> Date: Fri May 31 23:56:15 2024 +0800 some fix commit cc63926c8bb89df2d99d8c92c2e18bd5a0180a2c Author: blueloveTH <blueloveTH@foxmail.com> Date: Fri May 31 23:44:09 2024 +0800 some fix commit 3d3fb042651579cbdbcf3255398276ebb7b81e58 Author: blueloveTH <blueloveth@foxmail.com> Date: Fri May 31 17:28:13 2024 +0800 deprecate `PK_OBJ_MARK` commit 3df5f1cf128f157fb3a7aac2ceeeb47c55f5bb3b Author: blueloveTH <blueloveth@foxmail.com> Date: Fri May 31 17:18:34 2024 +0800 init
68 lines
1.5 KiB
Markdown
68 lines
1.5 KiB
Markdown
---
|
|
icon: dot
|
|
label: 'Create Modules'
|
|
order: 50
|
|
---
|
|
|
|
Modules are stored in `vm->_modules` and `vm->_lazy_modules`.
|
|
They are both dict-like objects.
|
|
|
|
### Lazy modules
|
|
|
|
A lazy module is a python source file.
|
|
It is compiled and executed when it is imported.
|
|
Use `[]` operator to add a lazy module.
|
|
|
|
```cpp
|
|
vm->_lazy_modules["test"] = "pi = 3.14";
|
|
```
|
|
|
|
```python
|
|
import test
|
|
print(test.pi) # 3.14
|
|
```
|
|
|
|
### Native modules
|
|
|
|
A native module is a module written in c++ or mixed c++/python.
|
|
Native modules are always compiled and executed when the VM is created.
|
|
|
|
To creata a native module, use `vm->new_module(Str name)`.
|
|
|
|
```cpp
|
|
PyObject* mod = vm->new_module("test");
|
|
mod->attr().set("pi", py_var(vm, 3.14));
|
|
|
|
vm->bind(mod, "add(a: int, b: int)",
|
|
[](VM* vm, ArgsView args){
|
|
int a = py_cast<int>(vm, args[0]);
|
|
int b = py_cast<int>(vm, args[1]);
|
|
return py_var(vm, a + b);
|
|
});
|
|
```
|
|
|
|
```python
|
|
import test
|
|
print(test.pi) # 3.14
|
|
print(test.add(1, 2)) # 3
|
|
```
|
|
|
|
### Module resolution order
|
|
|
|
When you do `import` a module, the VM will try to find it in the following order:
|
|
|
|
1. Search `vm->_modules`, if found, return it.
|
|
2. Search `vm->_lazy_modules`, if found, compile and execute it, then return it.
|
|
3. Try `vm->_import_handler`.
|
|
|
|
|
|
### Customized import handler
|
|
|
|
You can use `vm->_import_handler` to provide a custom import handler for the 3rd step.
|
|
|
|
### Import module via cpp
|
|
|
|
You can use `vm->py_import` to import a module.
|
|
This is equivalent to `import` in python.
|
|
Return the module object if success.
|