Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions include/pybind11/detail/class.h
Original file line number Diff line number Diff line change
Expand Up @@ -526,17 +526,17 @@ inline PyObject* make_new_python_type(const type_record &rec) {
#endif
}

object module;
object module_;
if (rec.scope) {
if (hasattr(rec.scope, "__module__"))
module = rec.scope.attr("__module__");
module_ = rec.scope.attr("__module__");
else if (hasattr(rec.scope, "__name__"))
module = rec.scope.attr("__name__");
module_ = rec.scope.attr("__name__");
}

auto full_name = c_str(
#if !defined(PYPY_VERSION)
module ? str(module).cast<std::string>() + "." + rec.name :
module_ ? str(module_).cast<std::string>() + "." + rec.name :
#endif
rec.name);

Expand Down Expand Up @@ -610,8 +610,8 @@ inline PyObject* make_new_python_type(const type_record &rec) {
else
Py_INCREF(type); // Keep it alive forever (reference leak)

if (module) // Needed by pydoc
setattr((PyObject *) type, "__module__", module);
if (module_) // Needed by pydoc
setattr((PyObject *) type, "__module__", module_);

PYBIND11_SET_OLDPY_QUALNAME(type, qualname);

Expand Down
12 changes: 6 additions & 6 deletions include/pybind11/detail/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,13 @@ extern "C" {
***Deprecated in favor of PYBIND11_MODULE***

This macro creates the entry point that will be invoked when the Python interpreter
imports a plugin library. Please create a `module` in the function body and return
imports a plugin library. Please create a `module_` in the function body and return
the pointer to its underlying Python object at the end.

.. code-block:: cpp

PYBIND11_PLUGIN(example) {
pybind11::module m("example", "pybind11 example plugin");
pybind11::module_ m("example", "pybind11 example plugin");
/// Set up bindings here
return m.ptr();
}
Expand All @@ -267,7 +267,7 @@ extern "C" {
This macro creates the entry point that will be invoked when the Python interpreter
imports an extension module. The module name is given as the fist argument and it
should not be in quotes. The second macro argument defines a variable of type
`py::module` which can be used to initialize the module.
`py::module_` which can be used to initialize the module.

.. code-block:: cpp

Expand All @@ -281,16 +281,16 @@ extern "C" {
}
\endrst */
#define PYBIND11_MODULE(name, variable) \
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module_ &); \
PYBIND11_PLUGIN_IMPL(name) { \
PYBIND11_CHECK_PYTHON_VERSION \
auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
auto m = pybind11::module_(PYBIND11_TOSTRING(name)); \
try { \
PYBIND11_CONCAT(pybind11_init_, name)(m); \
return m.ptr(); \
} PYBIND11_CATCH_INIT_EXCEPTIONS \
} \
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module_ &variable)


NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Expand Down
4 changes: 2 additions & 2 deletions include/pybind11/eigen.h
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
return false;

auto obj = reinterpret_borrow<object>(src);
object sparse_module = module::import("scipy.sparse");
object sparse_module = module_::import("scipy.sparse");
object matrix_type = sparse_module.attr(
rowMajor ? "csr_matrix" : "csc_matrix");

Expand Down Expand Up @@ -580,7 +580,7 @@ struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
const_cast<Type&>(src).makeCompressed();

object matrix_type = module::import("scipy.sparse").attr(
object matrix_type = module_::import("scipy.sparse").attr(
rowMajor ? "csr_matrix" : "csc_matrix");

array data(src.nonZeros(), src.valuePtr());
Expand Down
2 changes: 1 addition & 1 deletion include/pybind11/embed.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ inline void initialize_interpreter(bool init_signal_handlers = true) {
Py_InitializeEx(init_signal_handlers ? 1 : 0);

// Make .py files in the working directory available by default
module::import("sys").attr("path").cast<list>().append(".");
module_::import("sys").attr("path").cast<list>().append(".");
}

/** \rst
Expand Down
2 changes: 1 addition & 1 deletion include/pybind11/eval.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ object eval(str expr, object global = globals(), object local = object()) {
template <eval_mode mode = eval_expr, size_t N>
object eval(const char (&s)[N], object global = globals(), object local = object()) {
/* Support raw string literals by removing common leading whitespace */
auto expr = (s[0] == '\n') ? str(module::import("textwrap").attr("dedent")(s))
auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s))
: str(s);
return eval<mode>(expr, global, local);
}
Expand Down
8 changes: 4 additions & 4 deletions include/pybind11/iostream.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ NAMESPACE_END(detail)
.. code-block:: cpp

{
py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
py::scoped_ostream_redirect output{std::cerr, py::module_::import("sys").attr("stderr")};
std::cerr << "Hello, World!";
}
\endrst */
Expand All @@ -99,7 +99,7 @@ class scoped_ostream_redirect {
public:
scoped_ostream_redirect(
std::ostream &costream = std::cout,
object pyostream = module::import("sys").attr("stdout"))
object pyostream = module_::import("sys").attr("stdout"))
: costream(costream), buffer(pyostream) {
old = costream.rdbuf(&buffer);
}
Expand Down Expand Up @@ -130,7 +130,7 @@ class scoped_estream_redirect : public scoped_ostream_redirect {
public:
scoped_estream_redirect(
std::ostream &costream = std::cerr,
object pyostream = module::import("sys").attr("stderr"))
object pyostream = module_::import("sys").attr("stderr"))
: scoped_ostream_redirect(costream,pyostream) {}
};

Expand Down Expand Up @@ -190,7 +190,7 @@ NAMESPACE_END(detail)
m.noisy_function_with_error_printing()

\endrst */
inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
inline class_<detail::OstreamRedirect> add_ostream_redirect(module_ m, std::string name = "ostream_redirect") {
return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
.def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
.def("__enter__", &detail::OstreamRedirect::enter)
Expand Down
4 changes: 2 additions & 2 deletions include/pybind11/numpy.h
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ struct npy_api {
};

static npy_api lookup() {
module m = module::import("numpy.core.multiarray");
module_ m = module_::import("numpy.core.multiarray");
auto c = m.attr("_ARRAY_API");
#if PY_MAJOR_VERSION >= 3
void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
Expand Down Expand Up @@ -467,7 +467,7 @@ class dtype : public object {

private:
static object _dtype_from_pep3118() {
static PyObject *obj = module::import("numpy.core._internal")
static PyObject *obj = module_::import("numpy.core._internal")
.attr("_dtype_from_pep3118").cast<object>().release().ptr();
return reinterpret_borrow<object>(obj);
}
Expand Down
34 changes: 19 additions & 15 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -778,12 +778,12 @@ class cpp_function : public function {
};

/// Wrapper for Python extension modules
class module : public object {
class module_ : public object {
public:
PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)

/// Create a new top-level Python module with the given name and docstring
explicit module(const char *name, const char *doc = nullptr) {
explicit module_(const char *name, const char *doc = nullptr) {
if (!options::show_user_defined_docstrings()) doc = nullptr;
#if PY_MAJOR_VERSION >= 3
PyModuleDef *def = new PyModuleDef();
Expand All @@ -797,7 +797,7 @@ class module : public object {
m_ptr = Py_InitModule3(name, nullptr, doc);
#endif
if (m_ptr == nullptr)
pybind11_fail("Internal error in module::module()");
pybind11_fail("Internal error in module_::module_()");
inc_ref();
}

Expand All @@ -807,7 +807,7 @@ class module : public object {
details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
\endrst */
template <typename Func, typename... Extra>
module &def(const char *name_, Func &&f, const Extra& ... extra) {
module_ &def(const char *name_, Func &&f, const Extra& ... extra) {
cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
sibling(getattr(*this, name_, none())), extra...);
// NB: allow overwriting here because cpp_function sets up a chain with the intention of
Expand All @@ -822,34 +822,34 @@ class module : public object {

.. code-block:: cpp

py::module m("example", "pybind11 example plugin");
py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
py::module_ m("example", "pybind11 example plugin");
py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
\endrst */
module def_submodule(const char *name, const char *doc = nullptr) {
module_ def_submodule(const char *name, const char *doc = nullptr) {
std::string full_name = std::string(PyModule_GetName(m_ptr))
+ std::string(".") + std::string(name);
auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
if (doc && options::show_user_defined_docstrings())
result.attr("__doc__") = pybind11::str(doc);
attr(name) = result;
return result;
}

/// Import and return a module or throws `error_already_set`.
static module import(const char *name) {
static module_ import(const char *name) {
PyObject *obj = PyImport_ImportModule(name);
if (!obj)
throw error_already_set();
return reinterpret_steal<module>(obj);
return reinterpret_steal<module_>(obj);
}

/// Reload the module or throws `error_already_set`.
void reload() {
PyObject *obj = PyImport_ReloadModule(ptr());
if (!obj)
throw error_already_set();
*this = reinterpret_steal<module>(obj);
*this = reinterpret_steal<module_>(obj);
}

// Adds an object to the module using the given name. Throws if an object with the given name
Expand All @@ -866,12 +866,16 @@ class module : public object {
}
};

#if !defined(PYBIND11_CPP20)
using module = module_;
#endif

/// \ingroup python_builtins
/// Return a dictionary representing the global variables in the current execution frame,
/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
inline dict globals() {
PyObject *p = PyEval_GetGlobals();
return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
}

NAMESPACE_BEGIN(detail)
Expand Down Expand Up @@ -1816,7 +1820,7 @@ PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
file = kwargs["file"].cast<object>();
} else {
try {
file = module::import("sys").attr("stdout");
file = module_::import("sys").attr("stdout");
} catch (const error_already_set &) {
/* If print() is called from code that is executed as
part of garbage collection during interpreter shutdown,
Expand Down
2 changes: 1 addition & 1 deletion tests/constructor_stats.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ class ConstructorStats {
throw py::error_already_set();
Py_DECREF(result);
#else
py::module::import("gc").attr("collect")();
py::module_::import("gc").attr("collect")();
#endif
}

Expand Down
8 changes: 4 additions & 4 deletions tests/pybind11_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ productively.
Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions"
section of the documentation for good practice on splitting binding code over multiple files.
*/
std::list<std::function<void(py::module &)>> &initializers() {
static std::list<std::function<void(py::module &)>> inits;
std::list<std::function<void(py::module_ &)>> &initializers() {
static std::list<std::function<void(py::module_ &)>> inits;
return inits;
}

Expand All @@ -36,13 +36,13 @@ test_initializer::test_initializer(Initializer init) {
}

test_initializer::test_initializer(const char *submodule_name, Initializer init) {
initializers().push_back([=](py::module &parent) {
initializers().push_back([=](py::module_ &parent) {
auto m = parent.def_submodule(submodule_name);
init(m);
});
}

void bind_ConstructorStats(py::module &m) {
void bind_ConstructorStats(py::module_ &m) {
py::class_<ConstructorStats>(m, "ConstructorStats")
.def("alive", &ConstructorStats::alive)
.def("values", &ConstructorStats::values)
Expand Down
6 changes: 3 additions & 3 deletions tests/pybind11_tests.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ namespace py = pybind11;
using namespace pybind11::literals;

class test_initializer {
using Initializer = void (*)(py::module &);
using Initializer = void (*)(py::module_ &);

public:
test_initializer(Initializer init);
test_initializer(const char *submodule_name, Initializer init);
};

#define TEST_SUBMODULE(name, variable) \
void test_submodule_##name(py::module &); \
void test_submodule_##name(py::module_ &); \
test_initializer name(#name, test_submodule_##name); \
void test_submodule_##name(py::module &variable)
void test_submodule_##name(py::module_ &variable)


/// Dummy type which is not exported anywhere -- something to trigger a conversion error
Expand Down
4 changes: 2 additions & 2 deletions tests/test_class.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,12 @@ TEST_SUBMODULE(class_, m) {
struct MismatchDerived2 : MismatchBase2 { };

m.def("mismatched_holder_1", []() {
auto mod = py::module::import("__main__");
auto mod = py::module_::import("__main__");
py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
});
m.def("mismatched_holder_2", []() {
auto mod = py::module::import("__main__");
auto mod = py::module_::import("__main__");
py::class_<MismatchBase2>(mod, "MismatchBase2");
py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
MismatchBase2>(mod, "MismatchDerived2");
Expand Down
4 changes: 2 additions & 2 deletions tests/test_cmake_build/embed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ int main(int argc, char *argv[]) {

py::scoped_interpreter guard{};

auto m = py::module::import("test_cmake_build");
auto m = py::module_::import("test_cmake_build");
if (m.attr("add")(1, 2).cast<int>() != 3)
throw std::runtime_error("embed.cpp failed");

py::module::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp");
py::module_::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp");
py::eval_file(test_py_file, py::globals());
}
4 changes: 2 additions & 2 deletions tests/test_eigen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -319,11 +319,11 @@ TEST_SUBMODULE(eigen, m) {
// a new array (np.ones(10)) increases the chances that the temp array will be garbage
// collected and/or that its memory will be overridden with different values.
m.def("get_elem_direct", [](Eigen::Ref<const Eigen::VectorXd> v) {
py::module::import("numpy").attr("ones")(10);
py::module_::import("numpy").attr("ones")(10);
return v(5);
});
m.def("get_elem_indirect", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {
py::module::import("numpy").attr("ones")(10);
py::module_::import("numpy").attr("ones")(10);
return v[0](5);
});
}
Loading