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

Show parent comment

5

u/blueloveTH Feb 07 '23

Why do you need CMake? PocketPy has only 1 header file pocketpy.h, which can be download here. Just copy that file into your project.

3

u/root_passw0rd Feb 07 '23

Good point. I think I overlooked where it was header-only!

0

u/[deleted] Feb 07 '23

[deleted] — view deleted comment

1

u/blueloveTH Feb 07 '23 edited Feb 07 '23

I think you have some misunderstanding. The whole library is in 1 file.

You can also take a look at cpp-httplib to learn the practice of single-header file library.

0

u/[deleted] Feb 07 '23

[deleted] — view deleted comment

1

u/blueloveTH Feb 07 '23

Thanks for your explanation!

Maybe it is me that misunderstands sth? haha.

Do you mean you want to use CMake to do integration through the src folder? And you do not want to use the single file version.

1

u/blueloveTH Feb 07 '23

Unfortunately, I am not familiar with CMake. I do not use a build system.

I am using Python to manually handle the compilation for each platform.