Python enum string value

Fun With Python Enums

Published 2022-02-10. Last modified 2022-03-10.
Time to read: 3 minutes.

This blog post demonstrates how to define additional properties for Python 3 enums. Defining an additional property in a Python enum can provide a simple way to provide string values. The concept is then expanded to demonstrate composition, an important concept for functional programming. This post concludes with a demonstration of dynamic dispatch in Python, by further extending an enum.

Adding Properties to Python Enums

Searching for python enum string value yields some complex and arcane ways to approach the problem.

Below is a short example of a Python enum that demonstrates a simple way to provide lower-case string values for enum constants: a new property, to_s , is defined. This property provides the string representation that is required. You could define other properties and methods to suit the needs of other projects.

"""Defines enums""" 
from enum import Enum, auto
class EntityType(Enum): """Types of entities""" SITE = auto() GROUP = auto() COURSE = auto() SECTION = auto() LECTURE = auto()
@property def to_s(self) -> str: """:return: lower-case name of this instance""" return self.name.lower()

Adding the following to the bottom of the program allows us to demonstrate it:

if __name__ == "__main__": # Just for demonstration print("Specifying individual values:") print(f" : ") print(f" : ") print(f" : ") print(f" : ") print(f" : ") print("\nIterating through all values:") for entity_type in EntityType: print(f" : ")

Running the program produces this output:

$ cad_enums.py Specifying individual values: 1: site 2: group 3: course 4: section 5: lecture Iterating through all values: 1: site 2: group 3: course 4: section 5: lecture 

Constructing Enums

Enum constructors work the same as other Python class constructors. There are several ways to make a new instance of a Python enum. Let’s try two ways by using the Python interpreter. Throughout this blog post I’ve inserted a blank line between Python interpreter prompts for readability.

$ python Python 3.9.7 (default, Sep 10 2021, 14:59:43) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from cad_enums import EntityType >>> # Specify the desired enum constant value symbolically >>> gtype = EntityType.GROUP >>> print(gtype) EntityType.GROUP >>> # Specify the desired enum constant value numerically >>> stype = EntityType(1) >>> print(stype) EntityType.SITE 

Enum Ordering

A program I am working on needs to obtain the parent EntityType . By ‘parent’ I mean the EntityType with the next lowest numeric value. For example, the parent of EntityType.GROUP is EntityType.SITE . We can obtain a parent enum by computing its numeric value by adding the following method to the EntityType class definition.

@property def parent(self) -> 'EntityType': """:return: entity type of parent; site has no parent""" return EntityType(max(self.value - 1, 1))

The return type above is enclosed in quotes ( ‘EntityType’ ) to keep Python’s type checker happy, because this is a forward reference. This is a forward reference because the type is referenced before it is fully compiled.

The complete enum class definition is now:

"""Defines enums""" 
from enum import Enum, auto
class EntityType(Enum): """Types of entities""" SITE = auto() GROUP = auto() COURSE = auto() SECTION = auto() LECTURE = auto()
@property def to_s(self) -> str: """:return: lower-case name of this instance""" return self.name.lower()
@property def parent(self) -> 'EntityType': """:return: entity type of parent; site has no parent""" return EntityType(max(self.value - 1, 1))

Lets try out the new parent property in the Python interpreter.

Читайте также:  Learn php for web development

>>> EntityType.LECTURE.parent >>> EntityType.SECTION.parent >>> EntityType.COURSE.parent >>> EntityType.GROUP.parent >>> EntityType.SITE.parent

Enum Composition

Like methods and properties in all other Python classes, enum methods and properties compose if they return an instance of the class. Composition is also known as method chaining, and also can apply to class properties. Composition is an essential practice of a functional programming style.

The parent property returns an instance of the EntityType enum class, so it can be composed with any other property or method of that class, for example the to_s property shown earlier.

>>> EntityType.LECTURE.parent.to_s 'section' >>> EntityType.SECTION.parent.to_s 'course' >>> EntityType.COURSE.parent.to_s 'group' >>> EntityType.GROUP.parent.to_s 'site' >>> EntityType.SITE.parent.to_s 'site' 

Dynamic Dispatch

The Python documentation might lead someone to assume that writing dynamic dispatch code is more complex than it actually is.

To summarize the documentation, all Python classes, methods and instances are callable. Callable functions have type Callable[[InputArg1Type, InputArg2Type], ReturnType] . If you do not want any type checking, write Callable[. Any] . However, this is not very helpful information for dynamic dispatch. Fortunately, working with Callable is very simple.

You can pass around any Python class, constructor, function or method, and later provide it with the usual arguments. Invocation just works.

Let me show you how easy it is to write dynamic dispatch code in Python, let’s construct one of five classes, depending on the value of an enum. First, we need a class definition for each enum value:

# pylint: disable=too-few-public-methods class BaseClass(): """Demo only""" class TestLecture(BaseClass): """This constructor has type Callable[[int, str], TestLecture]""" def __init__(self, id_: int, action: str): print(f"CadLecture constructor called with id and action ") class TestSection(BaseClass): """This constructor has type Callable[[int, str], TestSection]""" def __init__(self, id_: int, action: str): print(f"CadSection constructor called with id and action ") class TestCourse(BaseClass): """This constructor has type Callable[[int, str], TestCourse]""" def __init__(self, id_: int, action: str): print(f"CadCourse constructor called with id and action ") class TestGroup(BaseClass): """This constructor has type Callable[[int, str], TestGroup]""" def __init__(self, id_: int, action: str): print(f"CadGroup constructor called with id and action ") class TestSite(BaseClass): """This constructor has type Callable[[int, str], TestSite]""" def __init__(self, id_: int, action: str): print(f"CadSite constructor called with id and action ")

Now lets add another method, called construct , to EntityType that invokes the appropriate constructor according to the value of an EntityType instance:

@property def construct(self) -> Callable: """:return: the appropriate Callable for each enum value""" if self == EntityType.LECTURE: return TestLecture if self == EntityType.SECTION: return TestSection if self == EntityType.COURSE: return TestCourse if self == EntityType.GROUP: return TestGroup return TestSite

Using named arguments makes your code resistant to problems that might sneak in due to parameters changing over time.

Читайте также:  Java get xml namespace

I favor using named arguments at all times; it avoids many problems. As code evolves, arguments might be added or removed, or even reordered.

Let’s test out dynamic dispatch in the Python interpreter. A class specific to each EntityType value is constructed by invoking the appropriate Callable and passing it named arguments id_ and action .

>>> EntityType.LECTURE.construct(id_=55, action="gimme_lecture") TestLecture constructor called with id 55 and action gimme_lecture >>> EntityType.SECTION.construct(id_=13, action="gimme_section") TestSection constructor called with id 13 and action gimme_section >>> EntityType.COURSE.construct(id_=40, action="gimme_course") TestCourse constructor called with id 40 and action gimme_course >>> EntityType.GROUP.construct(id_=103, action="gimme_group") TestGroup constructor called with id 103 and action gimme_group >>> EntityType.SITE.construct(id_=1, action="gimme_site") TestSite constructor called with id 1 and action gimme_site

Because these factory methods return the newly created instance of the desired type, the string representation is printed on the console after the method finishes outputting its processing results, for example: .

Using enums to construct class instances and/or invoke methods (aka dynamic dispatch) is super powerful. It rather resembles generics, actually, even though Python’s support for generics is still in its infancy.

The complete Python program discussed in this post is here.

Front Page Expert Witness Git Jekyll Documentation Jekyll Plugins Django / Oscar Ruby A/V Studio
Blog

Site Themes

  • Welcome!
  • Expert Witness
    • Overview
    • Articles
    • Biography
    • Resume: Word • PDF
    • Grouped by category
    • Sorted by date
    • Sorted by last modified
    • Organized
    • Sorted by last modified
    • Atom feed
    • Organized
    • Sorted by last modified
    • Atom feed
    • Organized
    • Sorted by last modified
    • Atom feed
    • Organized
    • Sorted by last modified
    • Atom feed
    • Organized
    • Sorted by last modified
    • Atom feed
    • Organized
    • Sorted by last modified
    • Atom feed

    Online

    Other Sites

    © Copyright 1994-2023 Michael Slinn. All rights reserved.
    For requests to use this copyright-protected work in any manner, email mslinn@mslinn.com.

    Источник

    How To Convert an Enum to a String in Python

    Convert an Enum to a String in Python

    To convert an enum to a string in Python, we have tested effectively with a combination of str() function and the type() method to confirm. In addition, you can use add a __str__ method into your Enum. Check out the details below to get more information.

    Convert an enum to a string in Python

    Using the str() function and use type() method to confirm

    To convert an enum to a string in Python, we can use the str() method to convert and use the type() method to make sure the enum is converted to a string.

    Str() function

    str(object, encoding=encoding, errors=errors)

    • object: is any object, specifies the object to convert into a string.
    • encoding: is the encoding of the object. The default is UTF-8.
    • errors: specifies what to do if the decoding fails.

    Return value: the return value is a string.

    Type() method

    • object: The object whose type is to be returned.
    • bases: is a tuple that itemizes the base class.
    • dict: a dictionary that holds the namespaces for the class.

    Return value: return value is the type of object in angular brackets.

    Code Example:

    Firstly we must import Enum. Then create the class Enum Animals. Secondly, we will use str() to convert the value of Enum Animals is int to string and use type() to print out the type of Enum after convert.

    from enum import Enum class Animals(Enum): SHARK = 1 DOLPHIN = 2 ELEPHANT = 3 for animal in Animals: print(type(animal.value)) print(animal.name, animal.value) print ("After converting Enum to string:") # Use the str method to convert int to string for animal in Animals: print(type(str(animal.value))) print(animal.name, animal.value)
     SHARK 1 DOLPHIN 2 ELEPHANT 3 After converting Enum to string: SHARK 1 DOLPHIN 2 ELEPHANT 3

    Add a __str__ method into your Enum

    Another way to convert an enum to a string in Python is you could add a __str__ method into the Enum and then convert the value int into a string.

    from enum import Enum class Animals(Enum): SHARK = 1 DOLPHIN = 2 ELEPHANT = 3 def __str__(self): return str(self.value) for animal in Animals: print(type(__str__(animal))) print(__str__(animal))

    Summary

    In this tutorial, we have explained how to convert an enum to a string in Python. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

    Maybe you are interested:

    My name is Fred Hall. My hobby is studying programming languages, which I would like to share with you. Please do not hesitate to contact me if you are having problems learning the computer languages Java, JavaScript, C, C#, Perl, or Python. I will respond to all of your inquiries.

    Name of the university: HUSC
    Major: IT
    Programming Languages: Java, JavaScript, C , C#, Perl, Python

    Источник

Оцените статью