You could just try opening the dataset/layer. Note that you don't need to tell GDAL about the GDB FeatureDataset.
If you want to actually roll your own exists function, you could do something like the following, but note that you will be opening the dataset twice, once when checking and again when opening for real. Which is not negligible when the dataset/layer is remote (i.e a URL) or in a zip file. Also note that this example doesn't handle GDAL raster subdatasets, but could fairly easily.
from osgeo import gdal
gdal.UseExceptions()
def exists(datasource, layer=None):
try:
ds = gdal.OpenEx(datasource)
if layer is not None:
return ds.GetLayerByName(layer) is not None
else:
return True
except RuntimeError as e:
return False
print(exists("exists.gdb", "existing_fc"))
print(exists("doesnt_exist.gdb", "no_such_fc"))
print(exists("exists.gdb", "no_such_fc"))
print(exists("exists.tif"))
print(exists("no_such.tif"))
Output:
True
False
False
True
False
If you do want to test the feature dataset part, you could do something like:
def exists(datasource, featuredataset=None, layer=None):
try:
ds = gdal.OpenEx(datasource)
if featuredataset is not None:
rg = ds.GetRootGroup()
fd = rg.OpenGroup(featuredataset)
if fd is not None:
if layer is not None: # Testing existence of layer inside featuredataset
return fd.OpenVectorLayer(layer) is not None
else:
return True # Testing existence of featuredataset
if layer is not None: # Testing existence of layer
return ds.GetLayerByName(layer) is not None
else:
return True # Testing existence of datasource
except RuntimeError as e:
return False
print(exists("exists.gdb", "existing_fd", "existing_fc"))
Output:
True # Note exists("exists.gdb", "existing_fc") will also return True even if it's in a feature dataset