Assign domain to a new or existing field using Python

Recently, I wrote a script to quickly add a new field to dozens of feature classes and assign a pre-existing coded value domain to it.

#
# @date 25/02/2015
# @author Cindy Williams
#
# Adds a new field to feature classes in a file GDB
# and assigns an existing domain to it. If the field
# exists, only the domain is assigned.
#
# For use in the Python window in ArcCatalog.
#
import arcpy
arcpy.env.workspace = r"C:\Some\Arb\Folder\work.gdb"
# Input variables
cvd = "cvd_District" # Name of existing coded value domain
field_nam = "District" # Name of new field to be added to feature class
for fc in arcpy.ListFeatureClasses():
try:
arcpy.management.AddField(in_table=fc,
field_name=field_nam,
field_type="SHORT",
field_alias=field_nam,
field_domain=cvd)
print("Added field and assigned domain to " + fc)
except:
print("Field exists in " + fc)
arcpy.management.AssignDomainToField(in_table=fc,
field_name=field_nam,
domain_name=cvd)
print("Domain assigned to " + fc)
print("Script complete.")

However, some of the feature classes already contained the field, which is why all the action happens within a try-except block.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.