arcpy – How to Correctly Reuse Field Properties with ArcPy

arcgis-proarcpy

I'm going through a feature class and attempting to catch all the fields and their properties, and reuse them in a new output feature class. Because I'm doing some stuff to the original data in-between, arcpy.CopyFeatures_management() doesn't work for me here.

My code:

in_fc = <the feature class>
d = arcpy.Describe(in_fc)
in_sr = d.spatialReference
in_fc_name = d.baseName

out_path = "C:/Temp/temp.gdb"
out_fc_name = f"{d.baseName}_edit"

out_fields = []
fields = arcpy.ListFields(in_fc)
for f in fields:
    if f.type == "String":
        field = [f.baseName, f.type, f.aliasName, f.length]
        out_fields.append(field)
    else:
        field = [f.baseName, f.type, f.aliasName, f.precision]
        out_fields.append(field)

# sanity check
for field in out_fields:
    print(field)  # all looks fine

out_fc = arcpy.CreateFeatureclass_management(proj_db, out_fc_name, f"{d.shapeType.upper()}", spatial_reference=in_sr)  # works

arcpy.AddFields_management(out_fc, fields)  # doesn't work

Fails with a convertArcObjectToPythonObject(gp.AddFields_management(*gp_fixargs((in_table, field_description), True))) and a runtime error.

Since the fields appear correct, and since the ArcPy documentation indicates that the Field type property is mapped to the AddFields_management() type parameter, (meaning I should be able to pass in "String" and have it parsed as "TEXT") I'm not sure where this is going wrong.

Best Answer

It seems you can skip the arcpy.AddFields_management() step if you simply include the template parameter in the arcpy.CreateFeatureclass_management() step.

Here is my test code, modified:

import arcpy
import os

proj_db = r"C:\Temp\project_database.gdb"
in_fc = r"C:\Temp\test_test123.gdb\test"
d = arcpy.Describe(in_fc)
in_sr = d.spatialReference
in_fc_name = d.baseName

out_fc_name = f"{d.baseName}_edit"
    
out_fc = arcpy.CreateFeatureclass_management(
        proj_db, 
        out_fc_name, 
        f"{d.shapeType.upper()}", 
        spatial_reference=in_sr, 
        template=in_fc
        )