- boost.python
- BuildingExtensions
- RecentChanges
- HelpContents
- Immutable Page
- Attachments

Building Extensions with boost.python
Using scons, using windows ide, using cmake, tips and tricks.

boost.python/BuildingExtensions (last edited 2012-02-13 18:30:15 by jeener )
- MoinMoin Powered
- Python Powered
- GPL licensed
- Valid HTML 4.01
Unable to edit the page? See the FrontPage for instructions.
Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Python module for boost::property_tree
eponymous/python3-property_tree
Name already in use.
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI .
- Open with GitHub Desktop
- Download ZIP
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Python bindings for boost::property_tree.
https://github.com/boostorg/property_tree
Tried to keep things pythonic so this isn't a 1:1 mapping to the C++ API
The property_tree.Tree class is a mix between a list and mapping structure so the python functions (mostly) match either 'list' or 'dict' where appropriate.
boost::property_tree is a header-only library so no runtime library dependencies
class Tree()
Property_tree.json, property_tree.xml.
- docs for property_tree.ini submodule
- docs for property_tree.info submodule
- Python 12.3%
Python Tutorial
File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python add class properties, add properties.
Add a property called graduationyear to the Student class:
In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function:
Add a year parameter, and pass the correct year when creating objects:
Related Pages

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top references, top examples, get certified.
- Main content
New York City will pay homeowners up to $395,000 to build an extra dwelling in their garage or basement to help ease the housing shortage
- New York City unveiled a pilot program to help homeowners build accessory dwelling units.
- The city will give 15 lucky homeowners up to $395,000 each to construct the extra unit.
- The New York State government has also handed out millions of dollars for ADU development.

As cities and towns across the country struggle with a housing shortage, policymakers are looking to legalize and even fund the construction of accessory dwelling units, or "granny flats," on existing residential property.
New York City just unveiled its newest effort , which will hand 15 homeowners up to $395,000 to build an additional apartment. This could mean an extra unit in a garage, basement, or attic, or a tiny home in the backyard. The idea is to boost housing density in a city in desperate need of new housing.
New Yorkers can apply online for the funding, but high-income residents aren't eligible — the income limit for a family of four is $232,980, the New York Times reported . And the ADUs that are built will have a limit on rent: a one-bedroom can't be rented for more than $2,600.
The city's department of housing preservation and development on Tuesday unveiled the "Plus One ADU" pilot program, similar to a state-wide initiative with the same name that has doled out tens of millions of dollars to help homeowners across New York State build ADUs in their backyards.
"Whether it's for seniors who need space for a caregiver, a multigenerational household who want separate living spaces, or young parents with a little one on the way, an ADU can offer the flexibility families need to make New York City work for them," New York City Mayor Eric Adams said in a statement.
The effort is part of the city's sweeping new housing reform proposal , which seeks to pave the way for 100,000 new homes in the city by encouraging conversions of commercial buildings into residential, boosting density near mass transit, and reducing space devoted to parking. The proposal also aims to legalize ADU construction across much more of the city.
New York City is facing an especially severe housing affordability crisis. Over the last 10 years, the Big Apple has created 800,000 new jobs, but just 200,000 new homes, according to the mayor. Now, half of New Yorkers are rent-burdened, meaning they spend more than 30% of their income on rent .
New York is following in the footsteps of states like California and Oregon, which have altered zoning laws and made other policy changes to encourage ADU construction.

Watch: Why it's so hard for millennials to buy homes


Exposing Classes
Now let's expose a C++ class to Python.
Consider a C++ class/struct that we want to expose to Python:
We can expose this to Python by writing a corresponding Boost.Python C++ Wrapper:
Here, we wrote a C++ class wrapper that exposes the member functions greet and set . Now, after building our module as a shared library, we may use our class World in Python. Here's a sample Python session:
Constructors
Our previous example didn't have any explicit constructors. Since World is declared as a plain struct, it has an implicit default constructor. Boost.Python exposes the default constructor by default, which is why we were able to write
We may wish to wrap a class with a non-default constructor. Let us build on our previous example:
This time World has no default constructor; our previous wrapping code would fail to compile when the library tried to expose it. We have to tell class_<World> about the constructor we want to expose instead.
init<std::string>() exposes the constructor taking in a std::string (in Python, constructors are spelled " " _init _" ").
We can expose additional constructors by passing more init<...> s to the def() member function. Say for example we have another World constructor taking in two doubles:
On the other hand, if we do not wish to expose any constructors at all, we may use no_init instead:
This actually adds an _init _ method which always raises a Python RuntimeError exception.
Class Data Members
Data members may also be exposed to Python so that they can be accessed as attributes of the corresponding Python class. Each data member that we wish to be exposed may be regarded as read-only or read-write . Consider this class Var :
Our C++ Var class and its data members can be exposed to Python:
Then, in Python, assuming we have placed our Var class inside the namespace hello as we did before:
Note that name is exposed as read-only while value is exposed as read-write .
Class Properties
In C++, classes with public data members are usually frowned upon. Well designed classes that take advantage of encapsulation hide the class' data members. The only way to access the class' data is through access (getter/setter) functions. Access functions expose class properties. Here's an example:
However, in Python attribute access is fine; it doesn't neccessarily break encapsulation to let users handle attributes directly, because the attributes can just be a different syntax for a method call. Wrapping our Num class using Boost.Python:
And at last, in Python:
Take note that the class property rovalue is exposed as read-only since the rovalue setter member function is not passed in:
Inheritance
In the previous examples, we dealt with classes that are not polymorphic. This is not often the case. Much of the time, we will be wrapping polymorphic classes and class hierarchies related by inheritance. We will often have to write Boost.Python wrappers for classes that are derived from abstract base classes.
Consider this trivial inheritance structure:
And a set of C++ functions operating on Base and Derived object instances:
We've seen how we can wrap the base class Base :
Now we can inform Boost.Python of the inheritance relationship between Derived and its base class Base . Thus:
Doing so, we get some things for free:
- Derived automatically inherits all of Base's Python methods (wrapped C++ member functions)
- If Base is polymorphic, Derived objects which have been passed to Python via a pointer or reference to Base can be passed where a pointer or reference to Derived is expected.
Now, we shall expose the C++ free functions b and d and factory :
Note that free function factory is being used to generate new instances of class Derived . In such cases, we use return_value_policy<manage_new_object> to instruct Python to adopt the pointer to Base and hold the instance in a new Python Base object until the the Python object is destroyed. We shall see more of Boost.Python call policies later.
Class Virtual Functions
In this section, we shall learn how to make functions behave polymorphically through virtual functions. Continuing our example, let us add a virtual function to our Base class:
One of the goals of Boost.Python is to be minimally intrusive on an existing C++ design. In principle, it should be possible to expose the interface for a 3rd party library without changing it. It is not ideal to add anything to our class Base . Yet, when you have a virtual function that's going to be overridden in Python and called polymorphically from C++ , we'll need to add some scaffoldings to make things work properly. What we'll do is write a class wrapper that derives from Base that will unintrusively hook into the virtual functions so that a Python override may be called:
Notice too that in addition to inheriting from Base , we also multiply- inherited wrapper < Base > (See Wrapper ). The wrapper template makes the job of wrapping classes that are meant to overridden in Python, easier.
BaseWrap's overridden virtual member function f in effect calls the corresponding method of the Python object through get_override .
Finally, exposing Base :
pure_virtual signals Boost.Python that the function f is a pure virtual function.
Virtual Functions with Default Implementations
We've seen in the previous section how classes with pure virtual functions are wrapped using Boost.Python's class wrapper facilities. If we wish to wrap non -pure-virtual functions instead, the mechanism is a bit different.
Recall that in the previous section , we wrapped a class with a pure virtual function that we then implemented in C++, or Python classes derived from it. Our base class:
had a pure virtual function f . If, however, its member function f was not declared as pure virtual:
We wrap it this way:
Notice how we implemented BaseWrap :: f . Now, we have to check if there is an override for f . If none, then we call Base :: f () .
Finally, exposing:
Take note that we expose both & Base :: f and & BaseWrap :: default_f . Boost.Python needs to keep track of 1) the dispatch function f and 2) the forwarding function to its default implementation default_f . There's a special def function for this purpose.
In Python, the results would be as expected:
Calling base.f() :
Calling derived.f() :
Class Operators/Special Functions
Python operators.
C is well known for the abundance of operators. C++ extends this to the extremes by allowing operator overloading. Boost.Python takes advantage of this and makes it easy to wrap C++ operator-powered classes.
Consider a file position class FilePos and a set of operators that take on FilePos instances:
The class and the various operators can be mapped to Python rather easily and intuitively:
The code snippet above is very clear and needs almost no explanation at all. It is virtually the same as the operators' signatures. Just take note that self refers to FilePos object. Also, not every class T that you might need to interact with in an operator expression is (cheaply) default-constructible. You can use other<T>() in place of an actual T instance when writing "self expressions".
Special Methods
Python has a few more Special Methods . Boost.Python supports all of the standard special method names supported by real Python class instances. A similar set of intuitive interfaces can also be used to wrap C++ functions that correspond to these Python special functions . Example:
Need we say more?
Boost C++ Libraries
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu , C++ Coding Standards

Chapter 2. High Level Components
Table of Contents
boost/python/class.hpp
Introduction.
< boost / python / class . hpp > defines the interface through which users expose their C++ classes to Python. It declares the class_ class template, which is parameterized on the class type being exposed. It also exposes the init , optional and bases utility class templates, which are used in conjunction with class_ .
< boost / python / class_fwd . hpp > contains a forward declaration of the class_ class template.
Class template class_ < T , Bases , HeldType , NonCopyable >
Creates a Python class associated with the C++ type passed as its first parameter. Although it has four template parameters, only the first one is required. The three optional arguments can actually be supplied in any order ; Boost.Python determines the role of the argument from its type.
HeldType Semantics
- If HeldType is derived from T , its exposed constructor(s) must accept an initial PyObject * argument which refers back to the Python object that contains the HeldType instance, as shown in this example. This argument is not included in the init-expression passed to def(init_expr) , below, nor is it passed explicitly by users when Python instances of T are created. This idiom allows C++ virtual functions which will be overridden in Python to access the Python object so the Python method can be invoked. Boost.Python automatically registers additional converters which allow wrapped instances of T to be passed to wrapped C++ functions expecting HeldType arguments.
- Because Boost.Python will always allow wrapped instances of T to be passed in place of HeldType arguments, specifying a smart pointer for HeldType allows users to pass Python T instances where a smart pointer-to-T is expected. Smart pointers such as std :: auto_ptr <> or boost :: shared_ptr <> which contain a nested type element_type designating the referent type are automatically supported; additional smart pointer types can be supported by specializing pointee < HeldType > .
- As in case 1 above, when HeldType is a smart pointer to a class derived from T , the initial PyObject * argument must be supplied by all of HeldType's exposed constructors.
- Except in cases 1 and 3, users may optionally specify that T itself gets initialized with a similar initial PyObject * argument by specializing has_back_reference<T> .
Class template class_ synopsis
Class template class_ constructors.
name is an ntbs which conforms to Python's identifier naming rules . If docstring is supplied, it must be an ntbs . If init_spec is supplied, it must be either the special enumeration constant no_init or an init-expression compatible with T .
Constructs a class_ object holding a Boost.Python extension class named name. The named attribute of the current scope is bound to the new extension class.
- If supplied, the value of docstring is bound to the __doc__ attribute of the extension class.
- If init_spec is no_init , a special __init__ function is generated which always raises a Python exception. Otherwise, this -> def ( init_spec ) is called.
- If init_spec is not supplied, this -> def ( init <>()) is called.
Allowing the user to specify constructor arguments in the class_ <> constructor helps her to avoid the common run-time errors which result from invoking wrapped member functions without having exposed an __init__ function which creates the requisite T instance. Types which are not default-constructible will cause a compile-time error unless Init is supplied. The user must always supply name as there is currently no portable method to derive the text of the class name from its type.
Class template class_ modifier functions
init_expr is the result of an init-expression compatible with T .
For each valid prefix P of Init , adds an __init__ (...) function overload to the extension class accepting P as arguments. Each overload generated constructs an object of HeldType according to the semantics described above, using a copy of init_expr's call policies. If the longest valid prefix of Init contains N types and init_expr holds M keywords, an initial sequence of the keywords are used for all but the first N - M arguments of each overload.
Allows users to easily expose a class' constructor to Python.
name is an ntbs which conforms to Python's identifier naming rules . * If a1 is the result of an overload-dispatch-expression , only the second form is allowed and fn must be a pointer to function or pointer to member function whose arity is the same as A1's maximum arity .
Effects: For each prefix P of Fn 's sequence of argument types, beginning with the one whose length is A1 's minimum arity , adds a name (...) method overload to the extension class. Each overload generated invokes a1's call-expression with P , using a copy of a1's call policies. If the longest valid prefix of A1 contains N types and a1 holds M keywords, an initial sequence of the keywords are used for all but the first N - M arguments of each overload.
- If fn is a function pointer, its first argument must be of the form U, U cv&, U cv*, or U cv* const&, where T* is convertible to U*, and a1-a3, if supplied, may be selected in any order from the table below.
- Otherwise, if fn is a member function pointer, its target must be T or one of its public base classes, and a1-a3, if supplied, may be selected in any order from the table below.
Otherwise, Fn must be [derived from] object , and a1-a2, if supplied, may be selcted in any order from the first two rows of the table below. To be useful, fn should be callable .
name is an ntbs which conforms to Python's identifier naming rules , and corresponds to a method whose overloads have all been defined.
Replaces the existing named attribute x with the result of invoking staticmethod ( x ) in Python. Specifies that the corresponding method is static and therefore no object instance will be passed to it. This is equivalent to the Python statement:
Attempting to invoke def(name,...) after invoking staticmethod(name) will raise a RuntimeError.
Adds a Python special method as described here .
name is an ntbs which conforms to Python's identifier naming rules .
Converts u to Python and adds it to the attribute dictionary of the extension class:
name is an ntbs which conform to Python's identifier naming rules .
Creates a new Python property class instance, passing object ( fget ) (and object ( fset ) in the second form) with an (optional) docstring doc to its constructor, then adds that property to the Python class object under construction with the given attribute name.
Allows users to easily expose functions that can be invoked from Python with attribute access syntax.
Creates a Boost.Python.StaticProperty object, passing object ( fget ) (and object ( fset ) in the second form) to its constructor, then adds that property to the Python class under construction with the given attribute name. StaticProperty is a special subclass of Python's property class which can be called without an initial self argument.
Allows users to easily expose functions that can be invoked from Python with static attribute access syntax.
name is an ntbs which conforms to Python's identifier naming rules . doc is also an ntbs .
respectively.
Allows users to easily expose a class' data member or free variable such that it can be inspected from Python with a natural syntax.
Allows users to easily expose a class' data or free variable member such that it can be inspected and set from Python with a natural syntax.
PickleSuite must be publically derived from pickle_suite .
Defines a legal combination of the special attributes and methods: __getinitargs__, __getstate__, __setstate__, __getstate_manages_dict__, __safe_for_unpickling__, __reduce__
Provides an easy to use high-level interface for establishing complete pickle support for the wrapped class. The user is protected by compile-time consistency checks.
Defines the __reduce__ method and the __safe_for_unpickling__ attribute.
Light-weight alternative to def_pickle(). Enables implementation of pickle support from Python.
Class template bases<T1, T2, ...TN>
An MPL sequence which can be used in class_<...> instantiations indicate a list of base classes.
Class template bases synopsis
Given a C++ class declaration:
A corresponding Boost.Python extension class can be created with:

IMAGES
VIDEO
COMMENTS
You can add a property to a class using a getter and a setter (in a simplistic case): class<X> ("X") .add_property ("foo", &X::get_foo, &X::set_foo); So then you can use it from python like this: >>> x = mymodule.X () >>> x.foo = 'aaa' >>> x.foo 'aaa' But how to add a property to a module itself (not a class)? There is
We can expose this to Python by writing a corresponding Boost.Python C++ Wrapper: #include <boost/python.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_<World> ("World") .def("greet", &World::greet) .def("set", &World::set) ; } Here, we wrote a C++ class wrapper that exposes the member functions greet and set.
Aug 27, 2020 at 7:41 There is a standard way of exposing C++ classes to Python with boost::python, have you tried it? (I personally recommend pybind11 over boost::python, the two packages are very similar in spirit so ideas and techniques carry over). - n. m. could be an AI Aug 27, 2020 at 8:09
Method 1 (old way) Method 2 (new way) "Raw" constructor Method 1 (official) Method 2 getter and setter methods as a property named constructors / factories (as Python initializers) boost.function objects a package within a single extension module How to get... C++ object from Python SWIG exposed C++ object from Python
BOOST_PYTHON_MODULE (nested_ext) { using namespace boost::python; // Establish X as the current scope. scope x_class ( class_<X> ("X", init<int> ()) .def (str (self)) ); // Y will now be defined in the current scope class_<Y> ("Y", init<int> ()) .def (str (self)) ; } We can even make a subclass of hello.world:
Welcome to Boost.Python, a C++ library which enables seamless interoperability between C++ and the Python programming language. The library includes support for: References and Pointers Globally Registered Type Coercions Automatic Cross-Module Type Conversions Efficient Function Overloading C++ to Python Exception Translation Default Arguments
Boost.Python Headers <boost/python/class.hpp>, <boost/python/class_fwd.hpp> Example (s) Introduction <boost/python/class.hpp> defines the interface through which users expose their C++ classes to Python. It declares the class template, which is parameterized on the class type being exposed.
python - How to add property to a class dynamically? - Stack Overflow How to add property to a class dynamically? Ask Question Asked 14 years, 3 months ago Modified 1 month ago Viewed 381k times 311 The goal is to create a mock class which behaves like a db resultset.
In Boost::Python, these are wrapped by instances of the boost::python::object class. If you need the underlying PyObject of any boost::python::object, you can get it via the ptr() method of boost::python::object, which returns a PyObject*. You can then use it in Python/C API calls. For example, to test if a boost::python::object called boostObj ...
Class Properties In C++, classes with public data members are usually frowned upon. Well designed classes that take advantage of encapsulation hide the class' data members. The only way to access the class' data is through access (getter/setter) functions. Access functions expose class Here's an example: struct Num { Num();
1 Requirements Boost.Python requires Python 2.2 1 or newer. 2 Background There are two basic models for combining C++ and Python: extending, in which the end-user launches the Python interpreter executable and imports Python "extension modules" written in C++.
It also has superior documentation compared to Boost.Python, and while it's API ... I've recently found out about pybind11, which is essentially a header only reimplementation of Boost.Python with C++11, and without any dependency on boost. ... property setter getter.add_property.def_readwrite: I need to replace :
Python Configuration Parameters If you have several versions of Python installed, or Python is installed in an unusual way, you may want to supply any or all of the following optional parameters to using python . version the version of Python to use. Should be in Major.Minor format, for example, 2.3.
Building Extensions with boost.python. Using bjam. bjam is a standard tool for building boost library itself. Thus it is preferable way to build Python extensions based on boost.python with bjam. Basic example listed in tutorial.. However if you want to add external libraries in your extension (that is why you use boost.python, isn't it?), you must add them to the Jamfile:
A property tree is a hierarchical data structure which has one data element in each node as well as an ordered sequence of sub-nodes which are additionally identified by a non-unique key. __init__ (self, value=None) -> Tree Creates a node with no children and a copy of the given data if provided. add (self, path, value) -> Tree Add a node at ...
Putting Python's property () Into Action Validating Input Values Providing Computed Attributes Caching Computed Attributes Logging Attribute Access and Mutation Managing Attribute Deletion Creating Backward-Compatible Class APIs Overriding Properties in Subclasses Conclusion Remove ads
Example Get your own Python Server. Add a property called graduationyear to the Student class: class Student (Person): def __init__ (self, fname, lname): super().__init__ (fname, lname) self.graduationyear = 2019. Try it Yourself ». In the example below, the year 2019 should be a variable, and passed into the Student class when creating ...
15 lucky New York City homeowners will get government funding to help boost housing density by adding an apartment to their property.
We can expose this to Python by writing a corresponding Boost.Python C++ Wrapper: #include <boost/python.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_<World> ("World") .def("greet", &World::greet) .def("set", &World::set) ; } Here, we wrote a C++ class wrapper that exposes the member functions greet and set.
Creates a Boost.Python.StaticProperty object, passing object (fget) (and object (fset) in the second form) to its constructor, then adds that property to the Python class under construction with the given attribute name. StaticProperty is a special subclass of Python's property class which can be called without an initial self argument.