Friday, April 27, 2012

Simple enum implementation in python

When using Arcpy, sometimes I always felts that the parameters that require specific entries, like workspace type for layer.replaceDataSource() would be best served if they were an enumerated value.
Python has rejected the enum type, but it does not mean you cannot create your own enum type. Let's get started:

 def __enum(**enums): 
    return type('Enum', (), enums)
Now we can define the enum values as needed.

WorkSpaceType = __enum(ACCESS_WORKSPACE="ACCESS_WORKSPACE",
                       ARCINFO_WORKSPACE="ARCINFO_WORKSPACE",
                       CAD_WORKSPACE="CAD_WORKSPACE",
                       EXCEL_WORKSPACE="EXCEL_WORKSPACE",
                       FILEGDB_WORKSPACE="FILEGDB_WORKSPACE",
                       NONE="NONE",
                       OLEDB_WORKSPACE="OLEDB_WORKSPACE",
                       PCCOVERAGE_WORKSPACE="PCCOVERAGE_WORKSPACE",
                       RASTER_WORKSPACE="RASTER_WORKSPACE",
                       SDE_WORKSPACE="SDE_WORKSPACE",
                       SHAPEFILE_WORKSPACE="SHAPEFILE_WORKSPACE",                     
                       TEXT_WORKSPACE="TEXT_WORKSPACE",
                       TIN_WORKSPACE="TIN_WORKSPACE",
                       VPF_WORKSPACE="VPF_WORKSPACE")

To use the newly created type, just call it like a property on any object.
>>> print WorkSpaceType.CAD_WORKSPACE
CAD_WORKSPACE

Enjoy

2 comments:

Brendan said...

Seems a bit awkward in python...what about just using class properties:

class WorkSpaceTypes(object):
ACCESS_WORKSPACE="ACCESS_WORKSPACE"
ARCINFO_WORKSPACE="ARCINFO_WORKSPACE"
CAD_WORKSPACE="CAD_WORKSPACE"
EXCEL_WORKSPACE="EXCEL_WORKSPACE"
FILEGDB_WORKSPACE="FILEGDB_WORKSPACE"
NONE="NONE"
OLEDB_WORKSPACE="OLEDB_WORKSPACE"
PCCOVERAGE_WORKSPACE="PCCOVERAGE_WORKSPACE"
RASTER_WORKSPACE="RASTER_WORKSPACE"
SDE_WORKSPACE="SDE_WORKSPACE"
SHAPEFILE_WORKSPACE="SHAPEFILE_WORKSPACE"
TEXT_WORKSPACE="TEXT_WORKSPACE"
TIN_WORKSPACE="TIN_WORKSPACE"
VPF_WORKSPACE="VPF_WORKSPACE"

Andrew said...

That works as well.