Skip to content

Commit

Permalink
Python bindings: Accept str arg in FeatureDefn.GetFieldDefn
Browse files Browse the repository at this point in the history
  • Loading branch information
dbaston committed Mar 17, 2024
1 parent 1f4ead7 commit 6c7592c
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 12 deletions.
15 changes: 15 additions & 0 deletions autotest/ogr/ogr_basic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,21 @@ def test_ogr_basic_16():
assert list(ogr_basic_16_gen_list(2)) == [0, 1]


def test_ogr_basic_getfielddefn():

defn = ogr.FeatureDefn()
defn.AddFieldDefn(ogr.FieldDefn("intfield", ogr.OFTInteger))

by_index = defn.GetFieldDefn(0)
by_name = defn.GetFieldDefn("intfield")

assert by_index.this == by_name.this

with gdaltest.enable_exceptions():
with pytest.raises(Exception, match="Invalid"):
defn.GetFieldDefn("does_not_exist")


def test_ogr_basic_invalid_unicode():

val = "\udcfc"
Expand Down
22 changes: 10 additions & 12 deletions swig/include/python/docs/ogr_featuredef_docs.i
Original file line number Diff line number Diff line change
Expand Up @@ -87,26 +87,24 @@ int:
count of fields.
";

%feature("docstring") GetFieldDefn "OGRFieldDefnH
OGR_FD_GetFieldDefn(OGRFeatureDefnH hDefn, int iField)
%feature("docstring") GetFieldDefn "
Fetch field definition of the passed feature definition.
This function is the same as the C++ method
OGRFeatureDefn::GetFieldDefn().
See :cpp:func:`OGRFeatureDefn::GetFieldDefn`.
Parameters
-----------
hDefn:
handle to the feature definition to get the field definition from.
iField:
the field to fetch, between 0 and GetFieldCount()-1.
i : int / str
Field name or 0-based numeric index. For repeated
access, use of the numeric index avoids a lookup
step.
Returns
--------
OGRFieldDefnH:
a handle to an internal field definition object or NULL if invalid
index. This object should not be modified or freed by the application.
FieldDefn:
internal field definition object or ``None`` if the field does not
exist. This object should not be modified by the application.
";

%feature("docstring") AddFieldDefn "void
Expand Down Expand Up @@ -548,4 +546,4 @@ int:
TRUE if the feature definition is identical to the other one.
";

}
}
5 changes: 5 additions & 0 deletions swig/include/python/ogr_python.i
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,11 @@ def ReleaseResultSet(self, sql_lyr):
self.thisown = 0

}

%feature("pythonprepend") GetFieldDefn %{
if type(args[0]) is str:
args = (self.GetFieldIndex(args[0]), )
%}
}

%extend OGRFieldDefnShadow {
Expand Down

0 comments on commit 6c7592c

Please sign in to comment.