###

# Boost.Python

## Header <boost/python/from_python.hpp>

## Contents

Introduction
Classes
  Class Template`from_python`
    Class Template `from_python` synopsis
    Class Template `from_python` constructor
    Class Template `from_python` observer functions
Example

## Introduction

`<boost/python/from_python.hpp>` introduces a class template `from_python<T>` for extracting a C++ object of type `T` from a Python object.

## Classes

### Class Template `from_python<class T>`

`from_python<T>` is the type used internally by Boost.Python to extract C++ function arguments from a Python argument tuple when calling a wrapped function. It can also be used directly to make similar conversions in other contexts.

#### Class Template `from_python` synopsis

    namespace boost { namespace python
    {
       template <class T>
       struct from_python : private boost::noncopyable // Exposition only.
           // from_python<T> meets the NonCopyable requirements
       {
          from_python(PyObject*);
          bool convertible() const;
          convertible-to-T operator()(PyObject*) const;
       };
    }

#### Class Template `from_python` constructor

    from_python(PyObject* p);

Requires: `p != 0`
Effects: Constructs a `from_python` object suitable for extracting a C++ object of type `T` from `p`.

#### Class Template `from_python` observer functions

    bool convertible() const;

Returns: `false` if the conversion cannot succeed. This indicates that either:
  1. No `from_python_converter` was registered for `T`, or
  2. any such converter rejected the constructor argument `p` by returning `0` from its `convertible()` function
  Note that conversion may still fail in `operator()` due to an exception.
Throws: nothing
Rationale: Because `from_python<>` is used in overload resolution, and throwing an exception can be slow, it is useful to be able to rule out a broad class of unsuccessful conversions without throwing an exception.

    convertible-to-T operator()(PyObject* p) const;

Requires: `*p` refers to the same object which was passed to the constructor, and `convertible()` returns `true`.
Effects: performs the conversion
Returns: an object convertible to `T`.

## Example

    #include <string>
    #include <boost/python/from_python.hpp>

    // If a std::string can be extracted from p, return its
    // length. Otherwise, return 0.
    std::size_t length_if_string(PyObject* p)
    {
       from_python<std::string> converter(p);
       if (!converter.convertible())
          return 0;
       else
          return converter(p).size();
    }

Revised 13 November, 2002

© Copyright Dave Abrahams 2002.