Welcome

sampleqa.in tutorials, Python Programming  tutorial

Python Enumerations


     Python Enumerations or enums are set of Symbolic Constants,Where each constant gets Unique ,constant Value

Enumerations are represented using class syntax.

Enumeration members can be compared by identity.

Enumeration objects are iteratable

Creating a Custom Enum class

     Enumerations follow class synatx and it should be derived from Enum class located in enum module

		import enum
		
		class employee_Type(enum.Enum):
		   FULL_TIME = 1
		   PART_TIME = 2
		   FREELANCER = 3
		   CONTRACT =  4
		   TEMPORARY = 5
	

Symbolic Names are FULL_TIME, PART_TIME,FREELANCER,CONTRACT and TEMPORARY. Each Symbolic Names has a value associated with it. i.e for FULL_TIME has value 1 ,for CONTRACT 4 etc., Users can assign any value of their choice.

Each Symbolic constant is called as a Member of employee_Type Enumberation. Each member has two fields called name and value
name is nothing but Symbolic Name, value is a number bound to it.

Accessing Members of Enumeration

     Each member can be accessed using
EnumType.SymbolicName syntax

Here enum Type is employee_type.
>>> employee_Type.FULL_TIME
<employee_Type.FULL_TIME: 1>

>>> type(employee_Type.FULL_TIME)
<enum 'employee_Type'>

>>> type(employee_Type.CONTRACT)
<enum 'employee_Type'>

>>> employee_Type.CONTRACT
<employee_Type.CONTRACT: 4>

>>> 
	

Each member is of type employee_Type. Note:Use type function to find the type of the object

Enum members properties/attributes

     Each enum symbolic name has 2 properties name and value
name returns Symbolic Name as a String object
value returns Number associated with that Symbolic Name.

>>> employee_Type.FULL_TIME.name
'FULL_TIME'

>>> employee_Type.FULL_TIME.value
1
>>>
      

Enumerations are iteratable

     Enumerations internally implement __itr__() and __next__() method for iterations. Programer can iterate all members using Manual Iteration or Automatic Iteration using for-each loop statement

Iterating using for-each loop
      >>> for etype in employee_Type:
...   print(etype)
... 
employee_Type.FULL_TIME
employee_Type.PART_TIME
employee_Type.CONTRACT
employee_Type.TEMPORARY
employee_Type.FREELANCER
      
Access name and value fields
>>> for etype in employee_Type:
...    print(etype.name,"-->",etype.value)
... 
FULL_TIME --> 1
PART_TIME --> 2
CONTRACT --> 4
TEMPORARY --> 5
FREELANCER --> 3
>>> 
Using format function
>>> for etype in employee_Type:
...    print("{0.name}-->{0.value}".format(etype))
... 
FULL_TIME-->1
PART_TIME-->2
CONTRACT-->4
TEMPORARY-->5
FREELANCER-->3
>>> 
	
Enumberation Symbolic Names can contain/bound to any other value , like str,float etc.,

class CityEnum(enum.Enum):
   CITY_NAME  =  'PARIS'
   LONGITUDE  =  43.4
   LATITUDE   =  45.6

ADS