2
0
mirror of https://github.com/boostorg/python.git synced 2026-01-20 16:52:15 +00:00

Compare commits

..

22 Commits

Author SHA1 Message Date
nobody
8e0553b310 This commit was manufactured by cvs2svn to create tag
'Version_1_31_0'.

[SVN r22162]
2004-02-04 15:24:32 +00:00
Joel de Guzman
ccc17a791a small typo
[SVN r22067]
2004-01-30 06:15:32 +00:00
Dave Abrahams
385fe03956 Improved and alphabetized news format, added Python news, updated
iterator news.

Corrections in the Python documentation


[SVN r22038]
2004-01-29 03:01:19 +00:00
Dave Abrahams
1727aa33b3 merged from HEAD
[SVN r22028]
2004-01-28 22:52:26 +00:00
Joel de Guzman
4c7694d81e small typo
[SVN r22026]
2004-01-28 22:45:35 +00:00
Ralf W. Grosse-Kunstleve
36751a0e0a merged from trun
[SVN r21716]
2004-01-14 01:39:40 +00:00
Ralf W. Grosse-Kunstleve
ccd909e98d previous revision (1.10) of this file restored because http://gcc.gnu.org/bugzilla/show_bug.cgi?id=13530 is fixed
[SVN r21633]
2004-01-12 18:02:28 +00:00
Joel de Guzman
01b25510ff fix typo
[SVN r21571]
2004-01-10 02:53:06 +00:00
Ralf W. Grosse-Kunstleve
06beca39af merged from trunk
[SVN r21559]
2004-01-09 07:26:47 +00:00
Dave Abrahams
65c10f8f08 merged from trunk
[SVN r21530]
2004-01-07 14:08:10 +00:00
Ralf W. Grosse-Kunstleve
3c1a4b13b7 merged from trunk: Test full slicing.
[SVN r21508]
2004-01-06 13:09:29 +00:00
Ralf W. Grosse-Kunstleve
157343241c merged from trunk: Workaround for gcc-3.4 quirks
[SVN r21507]
2004-01-06 13:08:25 +00:00
Dave Abrahams
11df3bc2d3 merged from trunk
[SVN r21473]
2004-01-04 13:41:34 +00:00
Dave Abrahams
469094ee45 merged from trunk
[SVN r21450]
2004-01-02 18:34:56 +00:00
Ralf W. Grosse-Kunstleve
ce3d43bb06 merged from trunk
[SVN r21448]
2004-01-02 18:06:01 +00:00
Dave Abrahams
3a3f5631b9 merged from trunk
[SVN r21443]
2004-01-01 12:46:39 +00:00
Ralf W. Grosse-Kunstleve
b6707c8e61 Merged from trunk: workaround for Visual C++ 6 internal compiler error
[SVN r21441]
2004-01-01 01:51:49 +00:00
Ralf W. Grosse-Kunstleve
3b25d2a78d Merged from trunk: workaround for g++ (GCC) 3.4.0 20031230 (experimental) problem
[SVN r21440]
2004-01-01 01:50:07 +00:00
Dave Abrahams
dba4d7bf72 merged from trunk
[SVN r21438]
2003-12-31 19:21:19 +00:00
Ralf W. Grosse-Kunstleve
bf86306f8b work around g++ (GCC) 3.4.0 20031230 (experimental) internal compiler error; http://gcc.gnu.org/bugzilla/show_bug.cgi?id=13530; in case this bug is not fixed before the gcc 3.4 release the boost 1.31.0 release should still compile
[SVN r21431]
2003-12-31 08:45:42 +00:00
Dave Abrahams
e782dd7e02 merged from trunk
[SVN r21430]
2003-12-31 00:25:37 +00:00
nobody
bd4fd372a0 This commit was manufactured by cvs2svn to create branch 'RC_1_31_0'.
[SVN r21427]
2003-12-30 12:10:04 +00:00
28 changed files with 27 additions and 875 deletions

View File

@@ -34,7 +34,6 @@ if [ check-python-config ]
dict.cpp
tuple.cpp
str.cpp
slice.cpp
aix_init_module.cpp
converter/from_python.cpp

View File

@@ -4,7 +4,6 @@
.. |(logo)| image:: ../../../c++boost.gif
:alt: Boost
:class: boost-logo
__ ../../../index.htm

View File

@@ -281,7 +281,6 @@ namespace boost { namespace python
// pickle support
template <typename PickleSuite>
self& def_pickle(PickleSuite const&);
self& enable_pickling();
};
}}
</pre>
@@ -710,21 +709,6 @@ class_&amp; def_pickle(PickleSuite const&amp;);
checks.</dt>
</dl>
<br>
<pre>
class_&amp; enable_pickling();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Defines the <code>__reduce__</code> method and
the <code>__safe_for_unpickling__</code> attribute.
<dt><b>Returns:</b> <code>*this</code></dt>
<dt><b>Rationale:</b> Light-weight alternative to
<code>def_pickle()</code>. Enables implementation of
<a href="pickle.html">pickle support</a> from Python.</dt>
</dl>
<br>
<h3><a name="bases-spec"></a>Class template

View File

@@ -208,19 +208,16 @@
<p><a name="slice_nil-spec"></a></p>
<pre>
class slice_nil;
static const _ = slice_nil();
enum slice_nil { _ };
</pre>
A type that can be used to get the effect of leaving out an index in a
Python slice expression:
<pre>
&gt;&gt;&gt; x[:-1]
&gt;&gt;&gt; x[::-1]
</pre>
C++ equivalent:
<pre>
x.slice(_,-1)
x[slice(_,_,-1)]
</pre>
<h2><a name="classes"></a>Classes</h2>

View File

@@ -281,51 +281,13 @@ is not empty.
</ul>
<hr>
<h2>Light-weight alternative: pickle support implemented in Python</h2>
<h3><a href="../../test/pickle4.cpp"><tt>pickle4.cpp</tt></a></h3>
The <tt>pickle4.cpp</tt> example demonstrates an alternative technique
for implementing pickle support. First we direct Boost.Python via
the <tt>class_::enable_pickling()</tt> member function to define only
the basic attributes required for pickling:
<pre>
class_&lt;world&gt;("world", args&lt;const std::string&amp;&gt;())
// ...
.enable_pickling()
// ...
</pre>
This enables the standard Python pickle interface as described
in the Python documentation. By &quot;injecting&quot; a
<tt>__getinitargs__</tt> method into the definition of the wrapped
class we make all instances pickleable:
<pre>
# import the wrapped world class
from pickle4_ext import world
# definition of __getinitargs__
def world_getinitargs(self):
return (self.get_country(),)
# now inject __getinitargs__ (Python is a dynamic language!)
world.__getinitargs__ = world_getinitargs
</pre>
See also the
<a href="../tutorial/doc/extending_wrapped_objects_in_python.html"
>tutorial section</a> on injecting additional methods from Python.
<hr>
&copy; Copyright Ralf W. Grosse-Kunstleve 2001-2004. Permission to copy,
&copy; Copyright Ralf W. Grosse-Kunstleve 20012-2002. Permission to copy,
use, modify, sell and distribute this document is granted provided this
copyright notice appears in all copies. This document is provided "as
is" without express or implied warranty, and with no claim as to its
suitability for any purpose.
<p>
Updated: Feb 2004.
Updated: Aug 2002.
</div>

View File

@@ -357,19 +357,6 @@
</dd>
</dl>
</dd>
<dt><a href="slice.html">slice.hpp</a></dt>
<dd>
<dl class="index">
<dt><a href="slice.html#classes">Classes</a></dt>
<dd>
<dl class="index">
<dt><a href="slice.html#slice-spec">slice</a></dt>
</dl>
</dd>
</dl>
</dd>
</dl>
<h2><a name="invocation">Function Invocation and Creation</a></h2>

View File

@@ -1,241 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="generator"
content="HTML Tidy for Windows (vers 1st August 2002), see www.w3.org">
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../boost.css">
<title>Boost.Python - &lt;boost/python/slice.hpp&gt;</title>
</head>
<body>
<table border="0" cellpadding="7" cellspacing="0" width="100%"
summary="header">
<tbody>
<tr>
<td valign="top" width="300">
<h3><a href="../../../../index.htm"><img height="86" width="277"
alt="C++ Boost" src="../../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center"><a href="../index.html">Boost.Python</a></h1>
<h2 align="center">Header &lt;boost/python/slice.hpp&gt;</h2>
</td>
</tr>
</tbody>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dd>
<dl class="page-index">
<dt><a href="#slice-spec">Class <code>slice</code></a></dt>
<dd>
<dl class="page-index">
<dt><a href="#slice-spec-synopsis">Class <code>slice</code>
synopsis</a></dt>
<dt><a href="#slice-spec-ctors">Class <code>slice</code>
constructors</a></dt>
<dt><a href="#slice-spec-observers">Class <code>slice</code>
observer functions</a></dt>
</dl>
</dd>
</dl>
</dd>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Exposes a <a href="ObjectWrapper.html#TypeWrapper-concept">TypeWrapper</a>
for the Python <a
href="http://www.python.org/doc/2.3.3/api/slice-objects.html">slice</a>
type.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-spec"></a>Class <code>slice</code></h3>
<p>Exposes the extended slicing protocol by wrapping the built-in slice
type. The semantics of the constructors and member functions defined
below can be fully understood by reading the <a
href="ObjectWrapper.html#TypeWrapper-concept">TypeWrapper</a> concept
definition. Since <code>slice</code> is publicly derived from <code><a
href="object.html#object-spec">object</a></code>, the public object
interface applies to <code>slice</code> instances as well.<br>
</p>
<h4><a name="slice-spec-synopsis"></a>Class <code>slice</code> synopsis</h4>
<pre>
namespace boost { namespace python
{
class slice : public object
{
public:
slice(); // create an empty slice, equivalent to [::]
template &lt;typename Int1, typename Int2&gt;
slice(Int1 start, Int2 stop);
template &lt;typename Int1, typename Int2, typename Int3&gt;
slice(Int1 start, Int2 stop, Int3 step);
// Access the parameters this slice was created with.
object start();
object stop();
object step();
// The return type of slice::get_indicies()
template &lt;typename RandomAccessIterator&gt;
struct range
{
RandomAccessIterator start;
RandomAccessIterator stop;
int step;
};
template &lt;typename RandomAccessIterator&gt;
range&lt;RandomAccessIterator&gt;
get_indicies(
RandomAccessIterator const&amp; begin,
RandomAccessIterator const&amp; end);
};
}}
</pre>
<h4><a name="slice-spec-ctors"></a>Class <code>slice</code>
constructors<br>
</h4>
<pre>slice();<br></pre>
<dl class="function-semantics">
<dt><b>Effects:</b> constructs a <code>slice</code> with default stop, start, and
step values.&nbsp; Equivalent to the slice object created by the Python
expression <code>base[::].</code></dt>
<dt><b>Throws:</b> nothing.</dt>
</dl>
<pre>
template &lt;typename Int1, typename Int2&gt;
slice(Int1 start, Int2 stop);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>start</code>, <code>stop</code>, and <code>step</code>
are of type <code>slice_nil</code> or convertible to type <code>object</code>.</dt>
<dt><b>Effects:</b> constructs a new slice with default step value
and the provided start and stop values.&nbsp; Equivalent to the slice
object
created by the built-in Python function <code><a
href="http://www.python.org/doc/current/lib/built-in-funcs.html#12h-62">slice(start,stop)</a></code>,
or the Python expression <code>base[start:stop]</code>.</dt>
<dt><b>Throws:</b> <code>error_already_set</code> and sets a Python <code>TypeError</code>
exception if no conversion is possible from the arguments to type <code>object</code>.</dt>
</dl>
<pre>
template &lt;typename Int1, typename Int2, typename Int3&gt;
slice(Int1 start, Int2 stop, Int3 step);
</pre>
<dt><b>Requires:</b> <code>start</code>, <code>stop</code>, and <code>step</code> are integers, <code>slice_nil</code>, or convertible to type <code>object</code>.</dt>
<dt><b>Effects:</b> constructs a new slice with start stop and step
values.&nbsp; Equivalent to the slice object created
by the built-in Python function <code><a
href="http://www.python.org/doc/current/lib/built-in-functions.html#12h-62">slice(start,stop,step)</a></code>,
or the Python expression <code>base[start:stop:step]</code>.</dt>
<dt><b>Throws:</b> <code>error_already_set</code> and sets a Python <code>TypeError</code>
exception if no conversion is possible from the arguments to type
object.</dt>
<h4><a name="slice-spec-observers"></a>Class <code>slice</code>
observer functions<br>
</h4>
<pre>
object slice::start();
object slice::stop();
object slice::step();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> None.</dt>
<dt><b>Throws:</b> nothing.</dt>
<dt><b>Returns:</b>the parameter that
the slice was created with.&nbsp;If the parameter was omitted or
slice_nil was used when the slice was created, than that parameter will
be a reference to PyNone and compare equal to a default-constructed
object.&nbsp;In principal, any object may be used when creating a
slice object, but in practice they are usually integers.</dt>
</dl>
<br>
<pre>
template &lt;typename RandomAccessIterator&gt;
slice::range&lt;RandomAccessIterator&gt;
slice::get_indicies(
RandomAccessIterator const&amp; begin, RandomAccessIterator const&amp; end);
</pre>
<dl class="function-semantics">
<dt><b>Arguments:</b> A pair of STL-conforming Random Access
Iterators that form a half-open range.</dt>
<dt><b>Effects:</b> Create a RandomAccessIterator pair that defines a
fully-closed range within the [begin,end) range of its arguments.&nbsp;
This function translates this slice's indicies while accounting for the
effects of any PyNone or negative indicies, and non-singular step sizes.</dt>
<dt><b>Returns:</b> a slice::range
that has been initialized with a non-zero value of step and a pair of
RandomAccessIterators that point within the range of this functions
arguments and define a closed interval.</dt>
<dt><b>Throws:</b> <a href="definitions.html#raise">Raises</a> a Python <code>TypeError</code> exception if any of this slice's arguments
are neither references to <code>PyNone</code> nor convertible to <code>int</code>.&nbsp; Throws
<code>std::invalid_argument</code> if the resulting range would be empty.&nbsp; You
should always wrap calls to <code>slice::get_indicies()</code>
within <code>try { ...; } catch (std::invalid_argument) {}</code> to
handle this case and take appropriate action.</dt>
<dt><b>Rationale</b>: closed-interval: If
an open interval were used, then for step
size other than 1, the required state for the end iterator would point
beyond the one-past-the-end position or before the beginning of the
specified range.<br>
exceptions on empty slice: It is impossible to define a closed interval
over an empty range, so some other form of error checking would have to
be used to prevent undefined behavior.&nbsp;In the case where the
exception is not caught, it will simply be translated to Python by the
default exception handling mechanisms. </dt>
</dl>
<h2><a name="examples"></a><b>Examples</b></h2>
<pre>
using namespace boost::python;
// Perform an extended slice of a Python list.
// Warning: extended slicing was not supported for built-in types prior
// to Python 2.3
list odd_elements(list l)
{
return l[slice(_,_,2)];
}
// Perform a multidimensional rich slice of a Numeric.array
numeric::array even_columns(numeric::array arr)
{
// select every other column, starting with the second, of a 2-D array.
// Equivalent to "return arr[:, 1::2]" in Python.
return arr[make_tuple( slice(), slice(1,_,2))];
}
// Perform a summation over a slice of a std::vector.
double partial_sum(std::vector&lt;double&gt; const&amp; Foo, slice index)
{
slice::range&lt;std::vector&lt;double&gt;::const_iterator&gt; bounds;
try {
bounds = index.get_indicies&lt;&gt;(Foo.begin(), Foo.end());
}
catch (std::invalid_argument) {
return 0.0;
}
double sum = 0.0;
while (bounds.start != bounds.end) {
sum += *bounds.start;
std::advance( bounds.start, bounds.step);
}
sum += *bounds.start;
return sum;
}
</pre>
<p>Revised 07 Febuary, 2004</p>
<p><i>&copy; Copyright <a
href="mailto:jbrandmeyer@users.sourceforge.net">Jonathan Brandmeyer</a>,
2004.&nbsp; Modification, copying and redistribution of this document
is permitted under the terms and conditions of the Boost Software
License, version 1.0.<br>
</i></p>
</body>
</html>

View File

@@ -415,12 +415,6 @@ class class_ : public objects::class_base
return *this;
}
self& enable_pickling()
{
this->base::enable_pickling_(false);
return *this;
}
self& staticmethod(char const* name)
{
this->make_method_static(name);

View File

@@ -32,7 +32,7 @@ struct BOOST_PYTHON_DECL class_base : python::api::object
// Implementation detail. Hiding this in the private section would
// require use of template friend declarations.
void enable_pickling_(bool getstate_manages_dict);
void enable_pickling(bool getstate_manages_dict);
protected:
void add_property(char const* name, object const& fget);

View File

@@ -59,7 +59,7 @@ namespace detail {
inaccessible* (*setstate_fn)(),
bool)
{
cl.enable_pickling_(false);
cl.enable_pickling(false);
cl.def("__getinitargs__", getinitargs_fn);
}
@@ -75,7 +75,7 @@ namespace detail {
void (*setstate_fn)(Tsetstate, Ttuple),
bool getstate_manages_dict)
{
cl.enable_pickling_(getstate_manages_dict);
cl.enable_pickling(getstate_manages_dict);
cl.def("__getstate__", getstate_fn);
cl.def("__setstate__", setstate_fn);
}
@@ -93,7 +93,7 @@ namespace detail {
void (*setstate_fn)(Tsetstate, Ttuple),
bool getstate_manages_dict)
{
cl.enable_pickling_(getstate_manages_dict);
cl.enable_pickling(getstate_manages_dict);
cl.def("__getinitargs__", getinitargs_fn);
cl.def("__getstate__", getstate_fn);
cl.def("__setstate__", setstate_fn);

View File

@@ -136,10 +136,7 @@ void* pointer_holder_back_reference<Pointer, Value>::holds(type_info dst_t)
/* --------------- pointer_holder --------------- */
#elif BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 1
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, pointer_holder.hpp)
# endif
# line BOOST_PP_LINE(__LINE__, pointer_holder.hpp)
# define N BOOST_PP_ITERATION()
@@ -156,10 +153,7 @@ void* pointer_holder_back_reference<Pointer, Value>::holds(type_info dst_t)
/* --------------- pointer_holder_back_reference --------------- */
#elif BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 2
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, pointer_holder.hpp(pointer_holder_back_reference))
# endif
# line BOOST_PP_LINE(__LINE__, pointer_holder.hpp(pointer_holder_back_reference))
# define N BOOST_PP_ITERATION()

View File

@@ -103,10 +103,7 @@ void* value_holder_back_reference<Value,Held>::holds(
// --------------- value_holder ---------------
#elif BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 1
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder))
# endif
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder))
# define N BOOST_PP_ITERATION()
@@ -125,10 +122,7 @@ void* value_holder_back_reference<Value,Held>::holds(
// --------------- value_holder_back_reference ---------------
#elif BOOST_PP_ITERATION_DEPTH() == 1 && BOOST_PP_ITERATION_FLAGS() == 2
# if !(BOOST_WORKAROUND(__MWERKS__, > 0x3100) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3201)))
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder_back_reference))
# endif
# line BOOST_PP_LINE(__LINE__, value_holder.hpp(value_holder_back_reference))
# define N BOOST_PP_ITERATION()

View File

@@ -13,6 +13,7 @@
# include <boost/python/call.hpp>
# include <boost/python/handle_fwd.hpp>
# include <boost/python/errors.hpp>
# include <boost/python/slice_nil.hpp>
# include <boost/python/refcount.hpp>
# include <boost/python/detail/preprocessor.hpp>
# include <boost/python/tag.hpp>
@@ -62,7 +63,6 @@ namespace api
struct item_policies;
struct const_slice_policies;
struct slice_policies;
class slice_nil;
typedef proxy<const_attribute_policies> const_object_attribute;
typedef proxy<attribute_policies> object_attribute;
@@ -471,6 +471,4 @@ inline PyObject* get_managed_object(object const& x, tag_t)
}} // namespace boost::python
# include <boost/python/slice_nil.hpp>
#endif // OBJECT_CORE_DWA2002615_HPP

View File

@@ -1,252 +0,0 @@
#ifndef BOOST_PYTHON_SLICE_JDB20040105_HPP
#define BOOST_PYTHON_SLICE_JDB20040105_HPP
// Copyright (c) 2004 Jonathan Brandmeyer
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python/object.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/converter/pytype_object_mgr_traits.hpp>
#include <iterator>
#include <algorithm>
namespace boost { namespace python {
class slice : public object
{
public:
// Equivalent to slice(::)
slice();
// Each argument must be int, slice_nil, or implicitly convertable to int
template<typename Integer1, typename Integer2>
slice( Integer1 start, Integer2 stop)
: object( boost::python::detail::new_reference(
PySlice_New( object(start).ptr(), object(stop).ptr(), NULL)))
{}
template<typename Integer1, typename Integer2, typename Integer3>
slice( Integer1 start, Integer2 stop, Integer3 stride)
: object( boost::python::detail::new_reference(
PySlice_New( object(start).ptr(), object(stop).ptr(),
object(stride).ptr())))
{}
// Get the Python objects associated with the slice. In principle, these
// may be any arbitrary Python type, but in practice they are usually
// integers. If one or more parameter is ommited in the Python expression
// that created this slice, than that parameter is None here, and compares
// equal to a default-constructed boost::python::object.
// If a user-defined type wishes to support slicing, then support for the
// special meaning associated with negative indicies is up to the user.
object start();
object stop();
object step();
// The following algorithm is intended to automate the process of
// determining a slice range when you want to fully support negative
// indicies and non-singular step sizes. Its functionallity is simmilar to
// PySlice_GetIndicesEx() in the Python/C API, but tailored for C++ users.
// This template returns a slice::range struct that, when used in the
// following iterative loop, will traverse a slice of the function's
// arguments.
// while (start != end) {
// do_foo(...);
// std::advance( start, step);
// }
// do_foo(...); // repeat exactly once more.
// Arguments: a [begin, end) pair of STL-conforming random-access iterators.
// Return: slice::range, where start and stop define a _closed_ interval
// that covers at most [begin, end-1] of the provided arguments, and a step
// that is non-zero.
// Throws: error_already_set() if any of the indices are neither None nor
// integers, or the slice has a step value of zero.
// std::invalid_argument if the resulting range would be empty. Normally,
// you should catch this exception and return an empty sequence of the
// appropriate type.
// Performance: constant time for random-access iterators.
// Rationale:
// closed-interval: If an open interval were used, then for a non-singular
// value for step, the required state for the end iterator could be
// beyond the one-past-the-end postion of the specified range. While
// probably harmless, the behavior of STL-conforming iterators is
// undefined in this case.
// exceptions on zero-length range: It is impossible to define a closed
// interval over an empty range, so some other form of error checking
// would have to be used by the user to prevent undefined behavior. In
// the case where the user fails to catch the exception, it will simply
// be translated to Python by the default exception handling mechanisms.
#ifndef BOOST_NO_MEMBER_TEMPLATES
template<typename RandomAccessIterator>
struct range
{
RandomAccessIterator start;
RandomAccessIterator stop;
int step;
};
template<typename RandomAccessIterator>
range<RandomAccessIterator>
get_indicies( const RandomAccessIterator& begin,
const RandomAccessIterator& end)
{
// This is based loosely on PySlice_GetIndicesEx(), but it has been
// carefully crafted to ensure that these iterators never fall out of
// the range of the container.
slice::range<RandomAccessIterator> ret;
typename RandomAccessIterator::difference_type max_dist =
std::distance( begin, end);
object slice_start = this->start();
object slice_stop = this->stop();
object slice_step = this->step();
// Extract the step.
if (slice_step == object()) {
ret.step = 1;
}
else {
ret.step = extract<int>( slice_step);
if (ret.step == 0) {
PyErr_SetString( PyExc_IndexError, "step size cannot be zero.");
throw_error_already_set();
}
}
// Setup the start iterator.
if (slice_start == object()) {
if (ret.step < 0) {
ret.start = end;
--ret.start;
}
else
ret.start = begin;
}
else {
int i = extract<int>( slice_start);
if (i >= max_dist && ret.step > 0)
throw std::invalid_argument( "Zero-length slice");
if (i >= 0) {
ret.start = begin;
std::advance( ret.start, std::min(i, max_dist-1));
}
else {
if (i < -max_dist && ret.step < 0)
throw std::invalid_argument( "Zero-length slice");
ret.start = end;
// Advance start (towards begin) not farther than begin.
std::advance( ret.start, (-i < max_dist) ? i : -max_dist );
}
}
// Set up the stop iterator. This one is a little trickier since slices
// define a [) range, and we are returning a [] range.
if (slice_stop == object()) {
if (ret.step < 0) {
ret.stop = begin;
}
else {
ret.stop = end;
std::advance( ret.stop, -1);
}
}
else {
int i = extract<int>( slice_stop);
// First, branch on which direction we are going with this.
if (ret.step < 0) {
if (i+1 >= max_dist || i == -1)
throw std::invalid_argument( "Zero-length slice");
if (i >= 0) {
ret.stop = begin;
std::advance( ret.stop, i+1);
}
else { // i is negative, but more negative than -1.
ret.stop = end;
std::advance( ret.stop, (-i < max_dist) ? i : -max_dist);
}
}
else { // stepping forward
if (i == 0 || -i >= max_dist)
throw std::invalid_argument( "Zero-length slice");
if (i > 0) {
ret.stop = begin;
std::advance( ret.stop, std::min( i-1, max_dist-1));
}
else { // i is negative, but not more negative than -max_dist
ret.stop = end;
std::advance( ret.stop, i-1);
}
}
}
// Now the fun part, handling the possibilites surrounding step.
// At this point, step has been initialized, ret.stop, and ret.step
// represent the widest possible range that could be traveled
// (inclusive), and final_dist is the maximum distance covered by the
// slice.
typename RandomAccessIterator::difference_type final_dist =
std::distance( ret.start, ret.stop);
// First case, if both ret.start and ret.stop are equal, then step
// is irrelevant and we can return here.
if (final_dist == 0)
return ret;
// Second, if there is a sign mismatch, than the resulting range and
// step size conflict: std::advance( ret.start, ret.step) goes away from
// ret.stop.
if ((final_dist > 0) != (ret.step > 0))
throw std::invalid_argument( "Zero-length slice.");
// Finally, if the last step puts us past the end, we move ret.stop
// towards ret.start in the amount of the remainder.
// I don't remember all of the oolies surrounding negative modulii,
// so I am handling each of these cases separately.
if (final_dist < 0) {
int remainder = -final_dist % -ret.step;
std::advance( ret.stop, remainder);
}
else {
int remainder = final_dist % ret.step;
std::advance( ret.stop, -remainder);
}
return ret;
}
#endif // !defined BOOST_NO_MEMBER_TEMPLATES
public:
// This declaration, in conjunction with the specialization of
// object_manager_traits<> below, allows C++ functions accepting slice
// arguments to be called from from Python. These constructors should never
// be used in client code.
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(slice, object)
};
namespace converter {
template<>
struct object_manager_traits<slice>
: pytype_object_manager_traits<&PySlice_Type, slice>
{
};
} // !namesapce converter
} } // !namespace ::boost::python
#endif // !defined BOOST_PYTHON_SLICE_JDB20040105_HPP

View File

@@ -7,19 +7,17 @@
# define SLICE_NIL_DWA2002620_HPP
# include <boost/python/detail/prefix.hpp>
# include <boost/python/object_core.hpp>
namespace boost { namespace python { namespace api {
class slice_nil : public object
{
public:
slice_nil() : object() {}
};
class object;
enum slice_nil
{
# ifndef _ // Watch out for GNU gettext users, who #define _(x)
static const slice_nil _ = slice_nil();
_
# endif
};
template <class T>
struct slice_bound

View File

@@ -253,13 +253,12 @@ class ClassExporter(Exporter):
constructors = [x for x in self.public_members if isinstance(x, Constructor)]
self.constructors = constructors[:]
# don't export constructors if the class is abstract
# don't export the copy constructor if the class is abstract
if self.class_.abstract:
for cons in constructors:
if cons.IsCopy():
constructors.remove(cons)
break
if not constructors:
# declare no_init
self.Add('constructor', py_ns + 'no_init')

View File

@@ -24,6 +24,8 @@ class EnumExporter(Exporter):
else:
self.enum = None
TYPE_COUNT = 0
def Export(self, codeunit, exported_names):
if not self.info.exclude:
indent = self.INDENT
@@ -32,10 +34,10 @@ class EnumExporter(Exporter):
full_name = self.enum.FullName()
unnamed_enum = False
if rename.startswith('$_') or rename.startswith('._'):
unique_number = hash(self.info.include)
unnamed_enum = True
self.ExportUniqueInt(codeunit)
full_name = namespaces.pyste + 'UniqueInt<%d>' % unique_number
full_name = namespaces.pyste + 'UniqueInt<%d>' % EnumExporter.TYPE_COUNT
EnumExporter.TYPE_COUNT += 1
rename = "unnamed"
code = indent + namespaces.python
code += 'enum_< %s >("%s")\n' % (full_name, rename)

View File

@@ -14,7 +14,7 @@ from VarExporter import VarExporter
from CodeExporter import CodeExporter
from exporterutils import FunctionWrapper
from utils import makeid
import warnings
#==============================================================================
# DeclarationInfo
@@ -149,7 +149,6 @@ class EnumInfo(DeclarationInfo):
class HeaderInfo(DeclarationInfo):
def __init__(self, include, exporter_class = HeaderExporter):
warnings.warn('AllFromHeader is not working in all cases in the current version.')
DeclarationInfo.__init__(self)
self._Attribute('include', include)
exporter = exporter_class(InfoWrapper(self))

View File

@@ -51,7 +51,7 @@ from CppParser import CppParser, CppParserError
import time
import declarations
__version__ = '0.9.29'
__version__ = '0.9.28'
def RecursiveIncludes(include):
'Return a list containg the include dir and all its subdirectories'

View File

@@ -12,7 +12,7 @@
#include <boost/lexical_cast.hpp>
#if defined(__APPLE__) && defined(__MACH__) && defined(__GNUC__) \
&& __GNUC__ == 3 && __GNUC_MINOR__ <= 4 && !defined(__APPLE_CC__)
&& __GNUC__ == 3 && __GNUC_MINOR__ == 3 && !defined(__APPLE_CC__)
# define BOOST_PYTHON_CONVERTER_REGISTRY_APPLE_MACH_WORKAROUND
#endif

View File

@@ -599,7 +599,7 @@ namespace objects
this->setattr("__init__", object(f));
}
void class_base::enable_pickling_(bool getstate_manages_dict)
void class_base::enable_pickling(bool getstate_manages_dict)
{
setattr("__reduce__", object(make_instance_reduce_function()));
setattr("__safe_for_unpickling__", object(true));

View File

@@ -1,38 +0,0 @@
#include "boost/python/slice.hpp"
// Copyright (c) 2004 Jonathan Brandmeyer
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
namespace boost { namespace python {
slice::slice()
: object( boost::python::detail::new_reference(
PySlice_New( NULL, NULL, NULL)))
{
}
object
slice::start()
{
return object( detail::borrowed_reference(
((PySliceObject*)this->ptr())->start));
}
object
slice::stop()
{
return object( detail::borrowed_reference(
((PySliceObject*)this->ptr())->stop));
}
object
slice::step()
{
return object( detail::borrowed_reference(
((PySliceObject*)this->ptr())->step));
}
} } // !namespace boost::python

View File

@@ -124,7 +124,6 @@ bpl-test crossmod_exception
[ bpl-test dict ]
[ bpl-test tuple ]
[ bpl-test str ]
[ bpl-test slice ]
[ bpl-test virtual_functions ]
[ bpl-test back_reference ]
@@ -151,7 +150,6 @@ bpl-test crossmod_exception
[ bpl-test pickle1 ]
[ bpl-test pickle2 ]
[ bpl-test pickle3 ]
[ bpl-test pickle4 ]
[ bpl-test nested ]
@@ -196,4 +194,4 @@ bpl-test crossmod_exception
[ compile-fail ./as_to_python_function.cpp <template>py-unit-test ]
[ compile-fail ./object_fail1.cpp <template>py-unit-test ]
;
}
}

View File

@@ -1,41 +0,0 @@
// Example by Ralf W. Grosse-Kunstleve
/*
This example shows how to enable pickling without using the
pickle_suite. The pickling interface (__getinitargs__) is
implemented in Python.
For more information refer to boost/libs/python/doc/pickle.html.
*/
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <string>
namespace {
// A friendly class.
class world
{
private:
std::string country;
public:
world(const std::string& country) {
this->country = country;
}
std::string greet() const { return "Hello from " + country + "!"; }
std::string get_country() const { return country; }
};
}
BOOST_PYTHON_MODULE(pickle4_ext)
{
using namespace boost::python;
class_<world>("world", init<const std::string&>())
.enable_pickling()
.def("greet", &world::greet)
.def("get_country", &world::get_country)
;
}

View File

@@ -1,36 +0,0 @@
r'''>>> import pickle4_ext
>>> import pickle
>>> def world_getinitargs(self):
... return (self.get_country(),)
>>> pickle4_ext.world.__getinitargs__ = world_getinitargs
>>> pickle4_ext.world.__module__
'pickle4_ext'
>>> pickle4_ext.world.__safe_for_unpickling__
1
>>> pickle4_ext.world.__name__
'world'
>>> pickle4_ext.world('Hello').__reduce__()
(<class 'pickle4_ext.world'>, ('Hello',))
>>> wd = pickle4_ext.world('California')
>>> pstr = pickle.dumps(wd)
>>> wl = pickle.loads(pstr)
>>> print wd.greet()
Hello from California!
>>> print wl.greet()
Hello from California!
'''
def run(args = None):
import sys
import doctest
if args is not None:
sys.argv = args
return doctest.testmod(sys.modules.get(__name__))
if __name__ == '__main__':
print "running..."
import sys
status = run()[0]
if (status == 0): print "Done."
sys.exit(status)

View File

@@ -1,83 +0,0 @@
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
using namespace boost::python;
// These checks are only valid under Python 2.3
// (rich slicing wasn't supported for builtins under Python 2.2)
bool check_string_rich_slice()
{
object s("hello, world");
// default slice
if (s[slice()] != "hello, world")
return false;
// simple reverse
if (s[slice(_,_,-1)] != "dlrow ,olleh")
return false;
// reverse with mixed-sign offsets
if (s[slice(-6,1,-1)] != " ,oll")
return false;
// all of the object.cpp check_string_slice() checks should work
// with the form that omits the step argument.
if (s[slice(_,-3)] != "hello, wo")
return false;
if (s[slice(-3,_)] != "rld")
return false;
if (", " != s[slice(5,7)])
return false;
return s[slice(2,-1)][slice(1,-1)] == "lo, wor";
}
// These tests work with Python 2.2, but you must have Numeric installed.
bool check_numeric_array_rich_slice()
{
using numeric::array;
object original = array( make_tuple( make_tuple( 11, 12, 13, 14),
make_tuple( 21, 22, 23, 24),
make_tuple( 31, 32, 33, 34),
make_tuple( 41, 42, 43, 44)));
object upper_left_quadrant = array( make_tuple( make_tuple( 11, 12),
make_tuple( 21, 22)));
object odd_cells = array( make_tuple( make_tuple( 11, 13),
make_tuple( 31, 33)));
object even_cells = array( make_tuple( make_tuple( 22, 24),
make_tuple( 42, 44)));
object lower_right_quadrant_reversed = array(
make_tuple( make_tuple(44, 43),
make_tuple(34, 33)));
// The following comments represent equivalent Python expressions used
// to validate the array behavior.
// original[::] == original
if (original[slice()] != original)
return false;
// original[:2,:2] == array( [[11, 12], [21, 22]])
if (original[make_tuple(slice(_,2), slice(_,2))] != upper_left_quadrant)
return false;
// original[::2,::2] == array( [[11, 13], [31, 33]])
if (original[make_tuple( slice(_,_,2), slice(_,_,2))] != odd_cells)
return false;
// original[1::2, 1::2] == array( [[22, 24], [42, 44]])
if (original[make_tuple( slice(1,_,2), slice(1,_,2))] != even_cells)
return false;
// original[:-3:-1, :-3,-1] == array( [[44, 43], [34, 33]])
if (original[make_tuple( slice(_,-3,-1), slice(_,-3,-1))] != lower_right_quadrant_reversed)
return false;
return true;
}
// Verify functions accepting a slice argument can be called
bool accept_slice( slice) { return true; }
BOOST_PYTHON_MODULE(slice_ext)
{
def( "accept_slice", accept_slice);
def( "check_numeric_array_rich_slice", check_numeric_array_rich_slice);
def( "check_string_rich_slice", check_string_rich_slice);
}

View File

@@ -1,60 +0,0 @@
"""
>>> from slice_ext import *
>>> accept_slice(slice(1, None, (1,2)))
1
>>> try:
... accept_slice(list((1,2)))
... print "test failed"
... except:
... print "test passed"
...
test passed
>>> have_numeric = 0
>>> try:
... from Numeric import array
... have_numeric = 1
... except:
... pass
...
>>> try:
... from numarray import array
... have_numeric = 1
... except:
... pass
...
>>> if have_numeric:
... check_numeric_array_rich_slice()
... else:
... print 1
...
1
>>> import sys
>>> if sys.version_info[0] == 2 and sys.version_info[1] >= 3:
... check_string_rich_slice()
... elif sys.version_info[0] > 2:
... check_string_rich_slice()
... else:
... print 1
...
1
"""
# Performs an affirmative and negative argument resolution check,
# checks the operation of extended slicing in Numeric arrays
# (only performed if Numeric.array or numarray.array can be found).
# checks the operation of extended slicing in new strings (Python 2.3 only).
def run(args = None):
import sys
import doctest
if args is not None:
sys.argv = args
return doctest.testmod(sys.modules.get(__name__))
if __name__ == '__main__':
print "running..."
import sys
status = run()[0]
if (status == 0): print "Done."
sys.exit(status)

View File

@@ -6,7 +6,6 @@
.. |(logo)| image:: ../../c++boost.gif
:alt: Boost
:class: boost-logo
__ ../../index.htm