- Immutable Page
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...
We read every piece of feedback, and take your input very seriously.
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
Python module for boost::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.
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.
Python bindings for boost::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
- docs for property_tree.ini submodule
- docs for property_tree.info submodule
- Python 12.3%
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:
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 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
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:
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 .
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:
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 () .
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
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".
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 > 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.
- 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 .
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: