MeshFunction unforgiving in type-check for __getitem__ and __setitem__

Issue #679 wontfix
Øyvind Evju created an issue

The type-check in MeshFunction.getitem/setitem checks only for python int, and therefore the following code fails for several numpy integer types (and long):

from dolfin import *
import numpy as np

mesh = UnitSquareMesh(4,4)
mesh.init(0,2)
cf = CellFunction("size_t", mesh)
v = Vertex(mesh, 0)

types = [int, long, np.int, np.int_, np.intc, np.intp, np.int8,
         np.int64, np.uint8, np.uint16, np.uint32, np.uint64]

for t in types:
    try:
        cf[t(1)] = 1
        assert cf[1] == 1
        print t, "succeeded"
    except:
        print t, "failed"
    cf[1] = 0

Simple fix would be to replace the following in swig/mesh/post.i:

def __setitem__(self, index, value):
    if not isinstance(index, (int, MeshEntity)):
        raise TypeError("expected an int or a MeshEntity as index argument")

and

def __getitem__(self, index, value):
    if not isinstance(index, (int, MeshEntity)):
        raise TypeError("expected an int or a MeshEntity as index argument")

with

def __getitem__(self, index):
    from numbers import Integral
    from numpy import integer
    if not isinstance(index, (Integral, integer, MeshEntity)):
        raise TypeError("expected an int-type or a MeshEntity as index argument")

and

def __setitem__(self, index, value):
    from numbers import Integral
    from numpy import integer
    if not isinstance(index, (Integral, integer, MeshEntity)):
        raise TypeError("expected an int-type or a MeshEntity as index argument")

Comments (9)

  1. Prof Garth Wells

    Tangentially related, I'd like to switch from std::size_t to the C++11 fixed width integers. It makes the Swig/NumPy wrapping simpler when the int width is fixed.

  2. Anders Logg (Chalmers)

    Yes that seems like the best choice. Should we make it a typedef this time? To ease the transition the next time we need to switch.

  3. Prof Garth Wells

    I don't think we should typedef it. std::size_t is a typedef, which is part of the problem since we need to wrap that something that we can't be sure of the size of. Moreover, a typedef may be incompatible with the format in a file.

    We can keep size_t, and deprecate it.

  4. Jan Blechta

    This must be solved in concert with #377 if @oyvinev's patch is to be applied. More precisely test for integer conversion are needed.

  5. Log in to comment