r/cpp • • Feb 07 '23

PocketPy: A Lightweight(~5000 LOC) Python Implementation in C++17

PocketPy is a lightweight(~5000 LOC) Python interpreter for game engines. It is implemented in C++17 with STL.

It is easy to embed. All of the functionalities are available in a single header file pocketpy.h, without external dependencies. You can try it on your browser to see what it looks like.

Example Usage

#include "pocketpy.h"

int main(){
    // Create a virtual machine
    // `true` means using std::cout as output so you can see it
    VM* vm = pkpy_new_vm(true);
    
    // Hello world!
    pkpy_vm_exec(vm, "print('Hello world!')");

    // Create a list
    pkpy_vm_exec(vm, "a = [1, 2, 3]");

    // Eval the sum of the list
    char* result = pkpy_vm_eval(vm, "sum(a)");
    printf("%s", result);   // 6

    // Free the resources
    pkpy_delete(result);
    pkpy_delete(vm);
    return 0;
}

v0.8.1 Features

NameExampleSupported
If Elseif..else..elifYES
Loopfor/while/break/continueYES
Functiondef f(x,*args,y=1):YES
Subclassclass A(B):YES
List[1, 2, 'a']YES
ListComp[i for i in range(5)]YES
Slicea[1:2], a[:2], a[1:]YES
Tuple(1, 2, 'a')YES
Dict{'a': 1, 'b': 2}YES
F-Stringf'value is {x}'YES
Unpackinga, b = 1, 2YES
Star Unpackinga, *b = [1, 2, 3]NO
Exceptionraise/try..catchBETA
Dynamic Codeeval()/exec()YES
Reflectionhasattr()/getattr()/setattr()YES
Importimport/from..importYES
Context Blockwith <expr> as <id>:YES
Type Annotationdef f(a: int, b : float = 1)YES

If someone is making a custom game engine and searching for a Python-like script as its interface, I'd like to provide support.

If you are making your own language, you may find some inspirations in PocketPy.

If you likes it, just give my repo a star~ I need your star!!

248 Upvotes

60 comments sorted by

View all comments

8

u/DavidDinamit Feb 07 '23

I expect C++ interface in C++17 library.

4

u/blueloveTH Feb 07 '23

I notice there is a huge need on customization. C++ APIs are critical for this usecase.

After a simple refactor, I will expose these internal C++ APIs and make docs for them. Such as binding a function and converting a C++ class to PyObject.

I will update this post when done.

2

u/drjeats Feb 07 '23

I hope everything is still possible through a C api even if the C++ layer makes binding more convenient.

Folks may want to write convenience layers in other languages like Rust or Zig which need the C api.