I am attempting to use Field/FieldMap/FieldMappings objects to add fields to a new feature class. In testing, it appears that the approach below is much faster than looping over a set of field settings and using the "AddField" geoprocessing tool, particularly for a large number of fields. Here I'm just testing one field.
Creating the geodatabase, the feature class, the domain (and the code) all work fine. So does adding the field (with some of the properties). What does not work is assigning the domain to the field--line 23 where I am assigning the domain using the "domain" property appears to have no effect. Additionally, trying to set a "defaultValue" throws an exception. Both of these properties appear to be writable according to the Field Object documentation:
Field—ArcGIS Pro | Documentation
Anyone know what's going on here, or what a workaround might be?
fldr = r"full\folder\path"
gdb = arcpy.management.CreateFileGDB(fldr, "TEST")
fc = arcpy.management.CreateFeatureclass("memory", "TEST_FC_MEMORY", "POLYGON")
arcpy.management.CreateDomain(in_workspace=gdb, domain_name="TEST_DOM",
domain_description="TEST", field_type="TEXT",
domain_type="CODED")
arcpy.management.AddCodedValueToDomain(in_workspace=gdb, domain_name="TEST_DOM",
code=1, code_description="A")
# Create Field, FieldMap, FieldMappings.
new_fld = arcpy.Field()
field_mapping = arcpy.FieldMap()
field_mappings = arcpy.FieldMappings()
new_fld.name = "TEST_FIELD"
new_fld.type = "String"
new_fld.length = 10
new_fld.aliasName = "ALIAS!"
new_fld.isNullable = False
# This doesn't seem to have any effect.
new_fld.domain = "TEST_DOM"
# This appears to be fine, but of course has no effect.
new_fld.madeUpAttribute = "X"
# Exception: NameError: The attribute 'defaultValue' is not
# supported on this instance of Field.
# new_fld.defaultValue = "X"
field_mapping.outputField = new_fld
field_mappings.addFieldMap(field_mapping)
arcpy.conversion.FeatureClassToFeatureClass(in_features=fc, out_path=gdb,
out_name="TEST_FC", field_mapping=field_mappings)
Feature class is created, domain is created with test code/description, and field is added (without the domain being assigned).