Skip to content

Instantly share code, notes, and snippets.

@cohnt
Created May 7, 2025 20:14
Show Gist options
  • Save cohnt/d5d7585b4d8a7102eb5cf659b27ed293 to your computer and use it in GitHub Desktop.
Save cohnt/d5d7585b4d8a7102eb5cf659b27ed293 to your computer and use it in GitHub Desktop.
Binding `static constexpr` in Python

Build with:

mkdir build
cd build
cmake ..
make

Then run the python script.

#include <pybind11/pybind11.h>
#include "constants.h"
namespace py = pybind11;
PYBIND11_MODULE(constexpr_demo, m) {
// Bind the namespace-level constexpr
m.attr("ERR_FAIL") = my_namespace::ERR_FAIL;
}
cmake_minimum_required(VERSION 3.14)
project(constexpr_demo)
# Enable C++17
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Find pybind11
find_package(pybind11 REQUIRED)
# Create the Python module
pybind11_add_module(constexpr_demo bindings.cc)
#pragma once
namespace my_namespace {
static constexpr int ERR_FAIL = 1;
}
import sys
import os
# Add the build directory relative to the script location
this_dir = os.path.dirname(os.path.abspath(__file__))
build_dir = os.path.join(this_dir, "build")
sys.path.insert(0, build_dir)
import constexpr_demo
print("Namespace constant:", constexpr_demo.ERR_FAIL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment