Checking if domain already exists using ArcPy?
The domains workspace property returns a Python list. If there are no domains in the workspace, then the list is empty:
>>> desc3 = arcpy.Describe(r'D:\Temp\NcLidar.gdb')
>>> domains3 = desc3.domains
>>> domains3
[]
If you have one domain, you get a list with a single element:
>>> desc2 = arcpy.Describe(r'D:\Projects\GDBs\scratch.gdb')
>>> domains2 = desc2.domains
>>>
>>> print domains2
[u'HU_Type Domain']
You could just check the length of the list and go from there:
>>> if len(domains3) > 0:
... print "we have domains"
... else:
... print "no domains"
...
no domains
Regarding the weirdness with the Exists
function, it does the same thing for me. Perhaps Exists
doesn't work for domains?
>>> if not arcpy.Exists(domains3):
... print domains3
...
[]
>>> if arcpy.Exists(domains3):
... print domains3
...
>>>
>>> if arcpy.Exists(domains2):
... print domains2
...
>>> if not arcpy.Exists(domains2):
... print domains2
...
[u'HU_Type Domain']
>>>
Since you are looking at a list of domains, it follows that if there are no domains, the list will be empty when populated. Therefore, choosing the next item in the list will return none. This provides an easy method to test for an empty list.
import arcpy
workspace = env.workspace = r"Z:\Test.gdb"
desc = arcpy.Describe(workspace)
domains = desc.domains
domain = None
domain = domains.next()
if not (domain == None):
print domain
else:
print "List empty"