1

I am working in ArcGIS Pro 3.2 and with Python 3.9.18

I am trying to replace the geometry of a polygon with the polygon from another layer. I have used this small calculate field expression to replace geometry and it works great!

enter image description here

I am hoping to create a tool so that individuals who are not as tech savvy can use it to replace geometry. I have tried to embed this expression into a script as shown:

import arcpy

def replaceGeometry(inLayer,geomLayer):
  fieldName = 'SHAPE'
  expression = "replaceGeometry()"
  codeblock = """
G = arcpy.Geometry()
geomList = arcpy.management.CopyFeatures('{geomLayer}',G)
def replaceGeometry():
  return geomList[0]"""
 

  # Run CalculateField 
  arcpy.management.CalculateField(in_table=inLayer,field= 'SHAPE', expression= 'replaceGeometry()',
                                expression_type= "PYTHON3", code_block= codeblock)

def script_tool(param0,param1):
  arcpy.AddMessage(f'The name of the Authoritative Layer chosen is: {param0}')
  arcpy.AddMessage(f'The name of the Geometry Layer chosen is: {param1}')
  replaceGeometry(param0,param1)


if __name__ == "__main__":

  param0 = arcpy.GetParameterAsText(0)
  param1 = arcpy.GetParameterAsText(1)

  script_tool(param0,param1)

I get this error:

NameError: name 'geomLayer' is not defined

Note: when I use the name of the layer in the expression it runs successfully as such:

  codeblock = """
G = arcpy.Geometry()
geomList = arcpy.management.CopyFeatures('Poly_2',G)
def replaceGeometry():
  return geomList[0]"""

So how do I correctly use param1 as a variable in the CalculateField method within a script tool? That way the layer is not hardcoded in.

1 Answer 1

1

I figured out the issue. I needed to make the code block an f string. Like this

import arcpy

arcpy.env.overwriteOutput = True


def replaceGeometry(inLayer,geomLayer):
  fieldName = 'SHAPE'
  expression = "replaceGeometry()"
  codeblock = f"""
G = arcpy.Geometry()
geomList = arcpy.management.CopyFeatures('{geomLayer}',G)
def replaceGeometry():
  return geomList[0]"""
 

  # Run CalculateField 
  arcpy.management.CalculateField(in_table=inLayer,field= 'SHAPE', expression= 'replaceGeometry()',
                                expression_type= "PYTHON3", code_block= codeblock)

def script_tool(param0,param1):
  arcpy.AddMessage(f'The name of the Authoritative Layer chosen is: {param0}')
  arcpy.AddMessage(f'The name of the Geometry Layer chosen is: {param1}')
  replaceGeometry(param0,param1)


if __name__ == "__main__":

  param0 = arcpy.GetParameterAsText(0)
  param1 = arcpy.GetParameterAsText(1)

  script_tool(param0,param1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.