Monday 22 January 2018

python - ogr: what is the advantage of using `geom.Clone()` over `geom`?


What is the advantage of using geom.Clone() over geom?


Simple example:


geom = link_feat.GetGeometryRef()

newfeature.SetGeometry(geom.Clone()) # or
newfeature.SetGeometry(geom)
layer.CreateFeature(newfeature)

Answer



From my experience the difference is subtle in that GetGeometryRef() will store a reference to the geometry which will be removed when the underlying feature is destroyed. If you use Clone() when storing the geometry you can access it and its methods even after destroying the feature.


To highlight this, suppose you want to open a shapefile, read a feature geometry, and print its WKT string.


# Open shapefile for reading and get layer object
import ogr
pth = r"C:\points.shp"
driver = ogr.GetDriverByName("ESRI Shapefile")

ds = driver.Open(pth,0)
lyr = ds.GetLayer()

# Get the first feature and print its WKT string
feat = lyr.GetNextFeature()
geom = feat.GetGeometryRef()
print geom.ExportToWkt()

# Destroy the feature and print its WKT again
feat.Destroy()

print geom.ExportToWkt()

The first print statement will successfully print the geometry's WKT string. That feature is then destroyed and, as a result, the following print statement will not work and Python may crash.


Now suppose the geom variable is set as follows:


geom = feat.GetGeometryRef().Clone()

In this case both print statements will be successful as the geom variable is storing a copy of the geometry itself. You can therefore destroy the feature and you will still be able to work with its geometry.


In your particular case, SetGeometry(geom) and SetGeometry(geom.Clone()) do the same thing since you do not destroy your link_feat. That said, were you to destroy link_feat before setting the newfeature geometry, neither of your SetFeature() calls would work because they themselves reference geom, which references link_feat, which would no longer exist.


Hope that helps. It really comes down to whether or not you want to work with the geometry after the feature has been destroyed.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...