Archive for the ‘python’ Category

Konwencja dostępu do iteratorów STL’u to para metod begin i end, gdzie pierwsza zwraca nam iterator początkowy, natomiast end zwraca iterator końca – dokładniej standard przewiduje, że end będzie określał element „za” ostatnim, ale teraz to nie jest najważniejsze. Myślę, że poniższa pętelka, to chleb powszedni czytelnika:

for( std::map<std::string,std::string>::iterator it = myMap.begin(); it != myMap.end(); it++){
// do some fancy stuff
}

Żeby jak najmniej zaskakiwać użytkownika naszego kodu, postanowiliśmy powielać tę konwencję i dostęp do naszych iteratorów także odbywa sie poprzez pary begin/end. Jednak wyobraźmy sobie sytuacje w której chcemy zwracać różne iteratory, np. mamy vector int’ow i chcemy przy pomocy jednego iteratora przejść przez liczby parzyste, inny umożliwia nam dostęp do nieparzystych, a trzeci do liczb podzielnych przez 5. Chwila zastanowienia i wygląda to na typowe zastosowanie faktorii, gdzie metoda fabrykująca dostaje parametr informujący o tym jaki typ iteratora interesuje użytkownika kodu zadeklarowany jako poniższy enum:

enum ITER{ODD,EVEN,DIV5};

Teraz tylko trzeba to dołączyć do naszego interfejsu i żeby elegancko schować całe to ustrojstwo trzeba dodać dodatkową metodę begin z parametrem, np:

class MyClass {
public:
public MyIterator begin( ITER type ) {}
}

Wszystko ładnie i pięknie, przyszedł moment eksportu api do pythona i jest problem, gdyż boost::python obsługuje jedynie standardowe pary begin/end. Eksport enum’a przy pomocy enum’a boost’owego to bułka z masłem, ale dalej nie da sie dobrać do iteratora innego niż domyślny, chwila 🙂 grzebaniny w źródłach samej bibliteki i mamy obsługę begin z parametrem przy pomocy kodu poniżej:


// Copyright David Abrahams 2002.
// Distributed under 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)
#ifndef ITERATOR_DWA2002512_HPP
# define ITERATOR_DWA2002512_HPP

# include <boost/python/detail/prefix.hpp>

# include <boost/python/detail/target.hpp>
# include <boost/python/object/iterator.hpp>
# include <boost/python/object_core.hpp>

# include <boost/type_traits/cv_traits.hpp>
# include <boost/type_traits/transform_traits.hpp>

# if defined(BOOST_MSVC) && (BOOST_MSVC == 1400) /*
> warning C4180: qualifier applied to function type has no meaning; ignored
Peter Dimov wrote:
This warning is caused by an overload resolution bug in VC8 that cannot be
worked around and will probably not be fixed by MS in the VC8 line. The
problematic overload is only instantiated and never called, and the code
works correctly. */
#  pragma warning(disable: 4180)
# endif

# include <boost/bind.hpp>
# include <boost/bind/protect.hpp>

namespace boost { namespace python {

namespace detail
{
  // Adds an additional layer of binding to
  // objects::make_iterator(...), which allows us to pass member
  // function and member data pointers.
  template <class Target, class Accessor1, class Accessor2, class NextPolicies>
  inline object make_iterator(
      Accessor1 get_start
    , Accessor2 get_finish
    , NextPolicies next_policies
    , Target&(*)()
  )
  {
      return objects::make_iterator_function<Target>(
          boost::protect(boost::bind(get_start, _1))
        , boost::protect(boost::bind(get_finish, _1))
        , next_policies
      );
  }

  template <class Arg, class Target, class Accessor1, class Accessor2, class NextPolicies>
  inline object make_iterator(
     Arg& arg
    , Accessor1 get_start
    , Accessor2 get_finish
    , NextPolicies next_policies
    , Target&(*)()
  )
  {
      return objects::make_iterator_function<Target, Arg>(
        boost::protect(boost::bind(get_start, _1, _2))
        , boost::protect(boost::bind(get_finish, _1))
        , next_policies
    	, arg
      );
  }

  // Guts of template class iterators<>, below.
  template <bool const_ = false>
  struct iterators_impl
  {
      template <class T>
      struct apply
      {
          typedef typename T::iterator iterator;
          static iterator begin(T& x) { return x.begin(); }
          static iterator end(T& x) { return x.end(); }
      };
  };

  template <>
  struct iterators_impl<true>
  {
      template <class T>
      struct apply
      {
          typedef typename T::const_iterator iterator;
          static iterator begin(T& x) { return x.begin(); }
          static iterator end(T& x) { return x.end(); }
      };
  };


  // guts of template class iterators<>, below.
  template <bool const_ = false>
  struct iterators_impl1
  {
      template <class t, class arg>
      struct apply
      {
          typedef typename t::iterator iterator;
          static iterator begin(t& x, arg y) { return x.begin(y); }
          static iterator end(t& x) { return x.end(); }
      };
  };

  template <>
  struct iterators_impl1<true>
  {
      template <class t, class arg>
      struct apply
      {
          typedef typename t::const_iterator iterator;
          static iterator begin(t& x, arg y) { return x.begin(y); }
          static iterator end(t& x) { return x.end(); }
      };
  };
}

// An "ordinary function generator" which contains static begin(x) and
// end(x) functions that invoke T::begin() and T::end(), respectively.
template <class T>
struct iterators
    : detail::iterators_impl<
        boost::is_const<T>::value
      >::template apply<T>
{
};

// An "ordinary function generator" which contains static begin(x, y) and
// end(x) functions that invoke T::begin(y) and T::end(), respectively.
// where y is extra argument when creating start iterator
template <class T, class Arg>
struct iterators1
    : detail::iterators_impl1<
        boost::is_const<T>::value
      >::template apply<T, Arg>
{
};

// Create an iterator-building function which uses the given
// accessors. Deduce the Target type from the accessors. The iterator
// returns copies of the inderlying elements.
template <class Accessor1, class Accessor2>
object range(Accessor1 start, Accessor2 finish)
{
    return detail::make_iterator(
        start, finish
      , objects::default_iterator_call_policies()
      , detail::target(start)
    );
}

// Create an iterator-building function which uses the given accessors
// and next() policies. Deduce the Target type.
template <class NextPolicies, class Accessor1, class Accessor2>
object range(Accessor1 start, Accessor2 finish, NextPolicies* = 0)
{
    return detail::make_iterator(start, finish, NextPolicies(), detail::target(start));
}

// Create an iterator-building function which uses the given accessors
// and next() policies, operating on the given Target type
template <class NextPolicies, class Target, class Accessor1, class Accessor2>
object range(Accessor1 start, Accessor2 finish, NextPolicies* = 0, boost::type<Target>* = 0)
{
    // typedef typename add_reference<Target>::type target;
    return detail::make_iterator(start, finish, NextPolicies(), (Target&(*)())0);
}

// Create an iterator-building function which uses the given accessors
// and next() policies. Deduce the Target type and Arg type.
template <class NextPolicies, class Accessor1, class Accessor2, class Arg>
object range(Accessor1 start, Accessor2 finish, Arg arg, NextPolicies* = 0)
{
    return detail::make_iterator(arg, start, finish, NextPolicies(), detail::target(start));
}

// A Python callable object which produces an iterator traversing
// [x.begin(), x.end()), where x is an instance of the Container
// type. NextPolicies are used as the CallPolicies for the iterator's
// next() function.
template <class Container
          , class NextPolicies = objects::default_iterator_call_policies>
struct iterator : object
{
    iterator()
        : object(
            python::range<NextPolicies>(
                &iterators<Container>::begin, &iterators<Container>::end
                ))
    {
    }
};

// A Python callable object which produces an iterator traversing
// [x.begin(y), x.end()), where x is an instance of the Container
// type and y is extra parameter that begin accepts when crating start
// iterator. NextPolicies are used as the CallPolicies for the iterator's
// next() function.
template <class Container, typename Arg
          , class NextPolicies = objects::default_iterator_call_policies>
struct iterator1 : object
{
	Arg arg;
    iterator1()
        : object(
            python::range<NextPolicies>(
                &iterators1<Container, Arg>::begin, &iterators<Container>::end, arg
                ))
    {
    }
};

}} // namespace boost::python

#endif // ITERATOR_DWA2002512_HPP


Teraz już możemy sobie bez większych problemów wyeksportować nasz iterator korzystając z konstrukcji:

.def("ints", bp::iterator1<IntWrapper,IntWrapperUtils::IteratorType>() );

Gdzie drugi argument to typ naszego iteratora.

Jeszcze tylko eksport enum’a, ale jak pisałem wyżej to prościzna 🙂

bp::enum_<IntWrapperUtils::IteratorType>("IteratorType")
.value( "ODD", IntWrapperUtils::ODD )
.value( "EVEN", IntWrapperUtils::EVEN )
.export_values()

I w skrypcie możemy już sobie wywoływać

for x in b.ints(IteratorType.EVEN):
print x

Voila 🙂