From 6c7592ca258b838ee2db04ca52656cc2e3de2e1e Mon Sep 17 00:00:00 2001 From: Daniel Baston Date: Sun, 17 Mar 2024 13:57:26 -0400 Subject: [PATCH] Python bindings: Accept str arg in FeatureDefn.GetFieldDefn --- autotest/ogr/ogr_basic_test.py | 15 +++++++++++++ .../include/python/docs/ogr_featuredef_docs.i | 22 +++++++++---------- swig/include/python/ogr_python.i | 5 +++++ 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/autotest/ogr/ogr_basic_test.py b/autotest/ogr/ogr_basic_test.py index fa00524fc6b8..48bc21a6093b 100755 --- a/autotest/ogr/ogr_basic_test.py +++ b/autotest/ogr/ogr_basic_test.py @@ -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" diff --git a/swig/include/python/docs/ogr_featuredef_docs.i b/swig/include/python/docs/ogr_featuredef_docs.i index 1de0b0e2f59f..f815381affb3 100644 --- a/swig/include/python/docs/ogr_featuredef_docs.i +++ b/swig/include/python/docs/ogr_featuredef_docs.i @@ -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 @@ -548,4 +546,4 @@ int: TRUE if the feature definition is identical to the other one. "; -} \ No newline at end of file +} diff --git a/swig/include/python/ogr_python.i b/swig/include/python/ogr_python.i index 35b10f57a9a0..3fe512a77125 100644 --- a/swig/include/python/ogr_python.i +++ b/swig/include/python/ogr_python.i @@ -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 {