Enums in Python & Pydantic | Python 3.11 StrEnum | Case-Insensitive enum with _missing_() method

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to explore the python enum type which we can use to store predefined values in an idiomatic way and as an example we're going to see how we can create a case insensitive enum by using the enums underscore Missing Method we'll also look at the python 3.11 string enum class and we're finally going to look at pantic and how we can integrate enums with pantic models so let's dive in so this short video will explore Python enums and this video will be something a little bit different it's going to be a shorter more concise video if you'd like more of this type of video just let me know in the comments now the idea in Python is that we have an enum that can represent a predefined set of values and enums they are available in most programming languages but as you can see in the documentation they were added to python in version 3.4 and an enum is a set of symbolic names that are bound to Unique values and you can see an example of that below we import the enum class and then we define a class that inherits from that enum in this example we have a class called color and that consists of three member variables we have red we have green and we have blue and these variables have symbolic names for example red but the value is one for red so when you have these types of values in your code but you don't want to refer to them just with the Primitive value 1 2 or three instead you can use the enum to refer to in a more idiomatic way that makes it more obvious what's going on in your application now in this we're going to learn how to make enum's case insensitive we're going to look at the underscore Missing Method on an enum we'll also see the python 3.11 string enum class and finally we're going to see how to use enums with pantic so let's start writing some code I'm going to go to vs code and I have a file here called main.py and I'm going to paste some code into this file and we're going to import the enum class from the enum module and then let's say we have an ordering system and we have an enum here called order status that enum contains four member variables and these represent different stages of an order so for example ordered shipped delivered or declined so four member variables within this enum now below the enum definition I'm going to add a print statement and let's say we wanted to look at an order status of delivered so what we need to do is we need to instantiate the enum and pass the string value that we want to actually use and that has to be something that's available as one of the members of that e so I'm going to pass in delivered here and what I'm going to do in the terminal is execute this program at the bottom so it's going to be Python and I've called the file main.py and you can see the output of that we have the enum field being output here and that's the order status. delivered field so these fields encapsulate a predefined set of possible values for an order status but the values have to be case sensitive so if I change this to a capital D and we rerun the script you can see we're get getting an error below here delivered is not a valid order status so we're going to need to change this up but let's say we have some some kind of requirement in our code we need to accept any kind of case so these have to be case insensitive now I'm going to show an example of how you might approach this problem in Python so the question is how do we make an enum case insensitive let's go back to the python documentation on enums and I'm going to search for a method that's available on the enum object and it's this method here it's underscore missing this is a class method that you can use for looking up values that are not found in the enum and by default this method will do nothing but if you need to implement some custom search behavior in your enum you can override this method and Define the logic and actually the logic for our code is what's defined here so what I'm going to do is just go back to vs code and we're going to write this up from scratch so let's do that now we're going to define a class method method in the enum and we need to call this underscore missing underscore now that takes two parameters the first one is the class because it's a class method it will take that as the first parameter and the second one is the value that's coming into the enum and this value if we get to the Missing Method here the value has not been found in any of the fields the members that are in the enum explicitly so the Missing Method allows you to kind of implement a custom search Logic if you encounter a value that is not in one of these fields and that's what we're going to do we're going to take the value and I'm going to lowercase it so let's create a variable here called value just by lower casing the value that's passed in what we can then do is we can actually iterate over all of the members in this enum and we can do that with a for Loop so I'm going to say for member in class and class refers to the enum that's coming in as the first parameter here so we can iterate over all of these members and now that we've lowercased the value being passed in what we can do is we can take each member and compare its value to the value that has been lowercased so let's write an if statement here if we have the member's value being equal to what we lower case on the line above here on line 11 in that case what we're going to do is we're going to return that member otherwise if we get to the end of the for Loop and we've not returned a member what we're going to do is just return none and that's because the value that's been lowercased after that lowercase operation and after that comparison we've not found a member so we're just going to return none and this this is actually all the code we need for a case insensitive enum in Python just by overwriting the underscore missing class method let's now go down here and I'm going to add a couple of extra Imports here a couple of extra print statements sorry and I'm going to change the casing of some of this so let's add one in all capitals one with a title case and I'm going to test this out with one of the other statuses that's the ordered status so let's add two more prints below and now once we've added those print statements we can actually execute the pro program and you can see we actually get back the enum members now so even though we're passing in values that don't match exactly the values for our enum members we're actually getting back the correct member because we've now added this underscore Missing Method that's going to perform the lower casing and then the equality search now there is one small optimization that we can make here but we need to be using python 3.1 in order to do that now I'm going to go to the documentation for the enom module and I'm going to search again and this time we're going to look for the string enum class that's been added so we've got that here we have a class called string enum available in enum module and this is exactly the same as an enum but the members are also strings now the small distinction here is that we have the members being printed out here but the actual value the underlying value for these members which is the string values here you have to call do value in order to access that so for example to get the underlying string value I would need to call Value on on the enum member and when we rerun that you can see at the top we actually get the string value represented by that member what we can do in Python 3.11 is we can import the string enum so I'm going to do that right at the top here and then we can subass that instead of the enum itself and what we can do then is change this line of code rather than looking at member. Value because the member is a string itself we can actually get rid of value here and we can just do the comparison against the member itself and I can also get rid of the DOT value that I just added here below and let's rerun the application and you can see that this time we get back the actual strings that are represented by each member so the very small distinction here is that the string enum its members are actually strings themselves and therefore we can reference those values and use string Methods on them just as we would with any other string and before we move on as well as string enum the enum module also comes with the int enum that you can use and the member variables are going to be integers let's move on to the final example of this short video we're going to see how to use an enum with pantic so what I'm going to do is activate a virtual environment with pantic installed and you can see that's been activated now if you need to install pantic you can use pip install pantic in order to do that what we're going to do is we're going to take this enum here that represents an order status and we're going to create a pantic model that uses that order status so from pantic at the top I'm going to import the pantic base model class and then we're going to define a model called order that inherits from the base model so this is a pantic model and let's say within that order for example we have a user and we're just going to make that a string and we also have a status and the status field we want to limit that to one of the order status options and I'm actually just going to move this uh pantic model below the order status here just so that it picks up that in vs code so we have an order status and and we are setting the status of the pantic model to one of the values in that enum so just below that what I'm going to do is get rid of these print statements and I'm going to add an order variable here and we're going to instantiate the order pantic model going to create an instance of that and we're going to pass a user of John do and we're going to pass a status here and let's say we're passing the status delivered now the status is delivered with a capital D it's en title case that does not match the casing on the delivered member but because of the underscore Missing Method this is actually going to be allowed and it's going to convert it to the correct member so let's test this out by printing out the order to the terminal and then we're going to run the script again it's Python main.py and when we run that we get back the pantic model that contains the username of John do and it contains that order status of delivered and we can change this status to any crazy looking casing that we want so if we have alternating capitals and lowercase letters that is still going to work because of our underscore Missing Method now of course if we control the status that's being passed into this order then we should use our enum so I'm going to use the order status enum and we can actually access the member directly so let's say order status. delivered so if we have control of that and we are controlling the values that are passed into the order we can actually refer to these directly when we run this script at the bottom that's still going to print out the same uh status as before and I mention this because of course sometimes a client is sending data so for example a client might send that crazy string here we don't control that we don't know what member that is we're just passing it into the pantic model and the model will then validate that against the type that is in this particular model for that field so I hope that makes sense if you have any questions let us know in the comments we've defined a case insensitive enum in this video by overriding the under _ Missing Method and implementing our search Logic here and in any circumstance where you are doing a lookup and an enum and you want to Define some kind of search Logic the underscore Missing Method can be useful for that so thank you for watching this video if you've enjoyed the video please give it a thumbs up and please subscribe to the channel if you've not already done so thanks again for watching and we'll see you in the next video
Info
Channel: BugBytes
Views: 3,772
Rating: undefined out of 5
Keywords:
Id: Y0g8iujY-GA
Channel Id: undefined
Length: 11min 27sec (687 seconds)
Published: Thu Dec 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.