Opened 10 years ago

Closed 10 years ago

#4758 closed defect (fixed)

In Python "if myLayer:" can reset feature iteration

Reported by: tbnorth Owned by: hobu
Priority: low Milestone: 1.10.0
Component: PythonBindings Version: unspecified
Severity: normal Keywords:
Cc:

Description

After some debugging with EvenR on IRC, we found that

    if myLayer:
        return myLayer.GetNextFeature()

behaves unexpectedly for some drivers (AVCbin for example) because if myLayer: calls myLayer.__len__() which calls GetFeatureCount which re-sets feature iteration for some drivers. So it's as if there's a hidden myLayer.ResetReading() before the return statement.

if myLayer is not None: is a workaround, but the surprise can be eliminated (it's hard to work out what's going on), if __notzero__ was defined on myLayer, that would be called before __len__. __notzero__ could possibly just return True all the time, seeing OGR seems to use None as the value to indicate a non-layer. See Python's __nonzero__ docs.

Usually a layer will only be tested once, immediately after GetLayer, so the current behaviour won't bother most people, but in cases where the layer is perhaps wrapped in a object feeding features to a client and if myLayer: is called repeatedly, the issue will interfere.

Change History (2)

comment:1 by Even Rouault, 10 years ago

Milestone: 2.0.0

Howard, I followed Terry's advice and went with :

r24709 /trunk/gdal/swig/ (include/python/ogr_python.i python/osgeo/ogr.py): Python bindings: define nonzero on Layer object to avoid GetFeatureCount() being called behind our back when doing 'if a_layer:' (#4758)

I don't think it might cause problems, except if people use "if a_layer:" to test if the layer is non empty, but that would seem an odd way to do so, wouldn't it ?

comment:2 by Even Rouault, 10 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.