diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index bcdf641f4..7c65a2ec8 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -1301,6 +1301,21 @@ public: // For Python 2, reinterpret_borrow was correct. return reinterpret_borrow(m); } + + struct strip_leading_underscore_from_name {}; + + module_ make_alias(const char *name) { + module_ ret = *this; + ret.attr("__name__") = name; + return ret; + } + + module_ make_alias(strip_leading_underscore_from_name) { + const char *name = PyModule_GetName(*this); + if (name && name[0] == '_') + name += 1; + return make_alias(name); + } }; PYBIND11_NAMESPACE_BEGIN(detail) diff --git a/tests/test_make_alias.cpp b/tests/test_make_alias.cpp new file mode 100644 index 000000000..487df8292 --- /dev/null +++ b/tests/test_make_alias.cpp @@ -0,0 +1,22 @@ +/* + tests/make_alias -- make alias + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include + +#include "constructor_stats.h" +#include "pybind11_tests.h" + +#if defined(_MSC_VER) +# pragma warning(disable : 4996) // C4996: std::unary_negation is deprecated +#endif + +TEST_SUBMODULE(_make_alias, m) { + ma = m.make_alias(pybind11::module::strip_leading_underscore_from_name{}); + ma.def("foo", []() -> {}); +} diff --git a/tests/test_make_alias.py b/tests/test_make_alias.py new file mode 100644 index 000000000..f8d4f6862 --- /dev/null +++ b/tests/test_make_alias.py @@ -0,0 +1,9 @@ +import pytest + +from pybind11_tests import ConstructorStats + +m = pytest.importorskip("pybind11_tests._make_alias") + + +def assert_name(mat): + assert m.__name__ == "make_alias"