Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nickrsan/0fa2bb57eed265b7995483d305284d65 to your computer and use it in GitHub Desktop.
Save nickrsan/0fa2bb57eed265b7995483d305284d65 to your computer and use it in GitHub Desktop.
Copies the attributes of a field (data type, precision, scale, length, isNullable, required, domain) to a new field on a new table. Correctly maps data types pulled from Describe tool to data types needed for field creation.
def copy_field_attributes_to_new_field(source_table, current_field, target_table, target_field):
"""
Copies the attributes of a field (data type, precision, scale, length, isNullable, required, domain) to a new field on a new table.
Correctly maps data types pulled from Describe tool to data types needed for field creation.
:param source_table: The table containing the existing field
:param current_field: The field to copy attributes from
:param target_table: The field to create the new field on
:param target_field: The name of the new field to create with the attributes from current_field
:return:
"""
# first, we need to find the information about the field that we're attaching
join_table_fields = arcpy.ListFields(source_table)
for field in join_table_fields:
if field.name == current_field: # we found our attribute
base_field = field
break
else:
raise ValueError("Couldn't find field to base join on in source table")
type_mapping = {"Integer": "LONG", "OID": "LONG", "SmallInteger": "SHORT",
"String": "TEXT"} # ArcGIS annoyingly doesn't report out the same data types as you need to provide, so this allows us to map one to the other
if base_field.type in type_mapping.keys(): # if it's a type that needs conversion
new_type = type_mapping[base_field.type] # look it up and save it
else:
new_type = base_field.type.upper() # otherwise, just grab the exact type as specified
if target_field:
new_name = target_field
else:
new_name = base_field.name
# copy the field over other than those first two attributes
arcpy.AddField_management(target_table, new_name, new_type, field.precision, field.scale, field.length,
field_alias=None, field_is_nullable=field.isNullable, field_is_required=field.required,
field_domain=field.domain)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment