mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-22 12:30:19 +00:00
...
This commit is contained in:
parent
196616a917
commit
4ec90dc5c6
@ -6,12 +6,25 @@ order: 70
|
||||
|
||||
pkpy uses a variant of the [Vectorcall](https://peps.python.org/pep-0590/) protocol (PEP 590).
|
||||
|
||||
There are 2 methods for calling a python function.
|
||||
You can use `call` to invoke any python callable object,
|
||||
including functions, methods, classes, etc.
|
||||
For methods, `call_method` can be used.
|
||||
|
||||
+ `PyObject* VM::call(PyObject* obj, ...)`
|
||||
+ `PyObject* VM::call_method(PyObject* obj, StrName name, ...)`
|
||||
|
||||
For example, to create a `dict` object,
|
||||
### Exmaple
|
||||
|
||||
Let's create a `dict` object and set a key-value pair,
|
||||
which equals to the following python snippet.
|
||||
|
||||
```python
|
||||
obj = {} # declare a `dict`
|
||||
obj["a"] = 5 # set a key-value pair
|
||||
print(obj["a"]) # print the value
|
||||
```
|
||||
|
||||
First, create an empty dict object,
|
||||
|
||||
```cpp
|
||||
PyObject* tp = vm->builtins->attr("dict");
|
||||
@ -22,6 +35,11 @@ And set a key-value pair,
|
||||
|
||||
```cpp
|
||||
vm->call_method(obj, "__setitem__", VAR("a"), VAR(5));
|
||||
PyObject* ret = vm->call(obj, "__getitem__", VAR("a"));
|
||||
std::cout << CAST(int, ret) << std::endl; // 5
|
||||
```
|
||||
|
||||
And get the value,
|
||||
|
||||
```cpp
|
||||
PyObject* ret = vm->call_method(obj, "__getitem__", VAR("a"));
|
||||
std::cout << CAST(i64, ret) << std::endl;
|
||||
```
|
@ -98,6 +98,17 @@ you can use the following functions:
|
||||
+ `bool is_tagged(PyObject* obj)`
|
||||
+ `bool is_non_tagged_type(PyObject* obj, Type type)`
|
||||
|
||||
```cpp
|
||||
PyObject* obj = VAR(1);
|
||||
|
||||
bool ok = is_type(obj, vm->tp_int); // true
|
||||
ok = is_int(obj); // true
|
||||
ok = is_tagged(obj); // true
|
||||
|
||||
ok = is_type(obj, vm->tp_float); // false
|
||||
ok = is_float(obj); // false
|
||||
```
|
||||
|
||||
Simply put, `is_type` is the most general function and can check any types.
|
||||
Other variants are designed for specific types and are faster.
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user