ArcPy Domains – Checking If Domain Already Exists

arcpydomainsesri-geodatabase

I am trying to check the existence of domains in my file geodatabase which contains 4 domains (automatically populated after I created some annotation feature classes). My code is as follows:

import arcpy

workspace = env.workspace = r"Z:\Test.gdb"

desc = arcpy.Describe(workspace)
domains = desc.domains

for domain in domains:
    if arcpy.Exists(domain):
        print domain

The issue I have is the behavior of the 'Exists' method'. When I set a conditional sentence to:

if arcpy.Exists(domain):
        print domain

the domains does not print. I'm thinking the code reads like 'If the domain exists, then print out the domain'. Because I have 4 domains, it should print these, but it doesn't.

I tried the reverse:

if not arcpy.Exists(domain):
        print domain

In this case, the domain gets printed out which seems counter intuitive. To me this reads like 'If the domain does not exists, then print the domain which should return nothing because it does not exist'

I want to test if any domains exists, instead of using a conditional statement to test if specific domains exist.

Best Answer

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']

>>>