Select to view content in your preferred language

Do the following python field checks exist?

542
2
03-14-2023 08:21 AM
ThomasColson
MVP Frequent Contributor

Looking for a python-way to check the existence of the following as part of a QA script:

  • If the correct default is assigned to a field;
  • If the field is nullable
  • If the field is required
Tags (3)
0 Kudos
2 Replies
Mahdi_Ch
Regular Contributor

I would do something like this in Python but there might be better ways: 

 

fields_ls = arcpy.ListFields(input_layer)

for f in fields_ls:
    if f.defaultValue == 'whatever':
        pass
    else:
        print(f'The defualt value for {f.name} is not equal whatever')

    if f.isNullable:
        print(f.name, 'nullable')
    if f.required:
        print(f.name, 'req')

 

 you can access other attributes from the field object too:

f.aliasName
f.baseName 
f.editable #bool
f.length
f.type 

 Generally one good way to check the possible attributes/methods to use on an object in Python is to to pass it to the dir() like this:

dir(fields_ls[1])

 and it prints all those for you! 

UPDATE: The way I did it was just to give you the idea how to access those info but was not scalable to check for default values of multiple fields. You should have a list or dictionary of default values to pass along. (The way @Anonymous User suggested in the comments is great!)

by Anonymous User
Not applicable

This should get you started.  Change out the defaults per field type in the dictionary.

 

 

import datetime
# Create a list of fields using the ListFields function
fields = arcpy.ListFields(in_Table)

defaultVal = {'Blob': 'stuff',
         'Date': datetime.datetime.now(),
         'Double': 54.2,
         'Geometry': 'Geometry',
         'GlobalID': 'Global ID',
         'Guid': 'Guid',
         'Integer': 23,
         'OID': 'Object ID',
         'Raster': 'Raster',
         'Single': 1,
         'SmallInteger': 3,
         'String': 'Text'}

# Iterate through the list of fields
for field in fields:
    # Not sure what Default value you are checking, but if they are different
    # for field types, you can set a dictionary and get it from there.
    
    print(f"Type: {field.type}")
    if field.defaultValue != defaultVal.get(field.defaultValue): # second param there is the defualt return if the key isnt found in the dictionary.
        print(f"Default Value: {field.defaultValue}")
    if field.isNullable: # True or False
        print(f"Is Nullable: {field.isNullable}")
    if field.required: # True or False
        print(f"Is Required: {field.required}")