Python 3: An Intro to Enumerations

Python added the enum module to the standard library in version 3.4. The Python documentation describes an enum like this:

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

Let’s look at how you might create an Enum object:

>>> from enum import Enum
>>> class AnimalEnum(Enum):
        HORSE = 1
        COW = 2
        CHICKEN = 3
        DOG = 4
>>> print(AnimalEnum.CHICKEN)
>>> print(repr(AnimalEnum.CHICKEN))
<AnimalEnum.CHICKEN: 3>

Here we create an Enumeration class called AnimalEnum. Inside the class, we create class attributes called enumeration members, which are constants. When you try to print out an enum member, you will just get back the same string. But if you print out the repr of the enum member, you will get the enum member and its value.

If you try to modify an enum member, Python will raise an AttributeError:

>>> AnimalEnum.CHICKEN = 5
Traceback (most recent call last):
  Python Shell, prompt 5, line 1
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 361, in __setattr__
    raise AttributeError('Cannot reassign members.')
builtins.AttributeError: Cannot reassign members.

Enum members have some properties you can use to get their name and value:

>>> AnimalEnum.CHICKEN.value

Enumerations also support iteration. So you can do something fun like this:

>>> for animal in AnimalEnum:
        print('Name: {}  Value: {}'.format(animal, animal.value))
Name: AnimalEnum.HORSE  Value: 1
Name: AnimalEnum.COW  Value: 2
Name: AnimalEnum.CHICKEN  Value: 3
Name: AnimalEnum.DOG  Value: 4

Python’s enumerations do not allow you to create enum members with the same name:

>>> class Shapes(Enum):
...     CIRCLE = 1
...     SQUARE = 2
...     SQUARE = 3
Traceback (most recent call last):
  Python Shell, prompt 13, line 1
  Python Shell, prompt 13, line 4
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 92, in __setitem__
    raise TypeError('Attempted to reuse key: %r' % key)
builtins.TypeError: Attempted to reuse key: 'SQUARE'

As you can see, when you try to reuse an enum member name, it will raise a TypeError.

You can also create an Enum like this:

>>> AnimalEnum = Enum('Animal', 'HORSE COW CHICKEN DOG')
>>> AnimalEnum
<enum 'Animal'>
>>> AnimalEnum.CHICKEN
<Animal.CHICKEN: 3>

Personally, I think that is really neat!

Enum Member Access

Interestingly enough, there are multiple ways to access enum members. For example, if you don’t know which enum is which, you can just call the enum directly and pass it a value:

>>> AnimalEnum(2)
<AnimalEnum.COW: 2>

If you happen to pass in an invalid value, then Python raises a ValueError

>>> AnimalEnum(8)
Traceback (most recent call last):
  Python Shell, prompt 11, line 1
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 291, in __call__
    return cls.__new__(cls, value)
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 533, in __new__
    return cls._missing_(value)
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
builtins.ValueError: 8 is not a valid AnimalEnum

You may also access an enumeration by name:

>>> AnimalEnum['CHICKEN']
<AnimalEnum.CHICKEN: 3>

Enum Niceties

The enum module also has a couple of other fun things you can import. For example, you can can create automatic values for your enumerations:

>>> from enum import auto, Enum
>>> class Shapes(Enum):
        CIRCLE = auto()
        SQUARE = auto()
        OVAL = auto() 
>>> Shapes.CIRCLE
<Shapes.CIRCLE: 1>

You can also import a handy enum decorator to make sure that your enumeration members are unique:

>>> @unique
    class Shapes(Enum):
        CIRCLE = 1
        SQUARE = 2
        TRIANGLE = 1
Traceback (most recent call last):
  Python Shell, prompt 18, line 2
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\", line 830, in unique
    (enumeration, alias_details))
builtins.ValueError: duplicate values found in <enum 'Shapes'>: TRIANGLE -> CIRCLE

Here we create an enumeration that has two members trying to map to the same value. Because we added the @unique decorator, a ValueError is raised if there are any duplicate values in the enum members. If you do not have the @unique decorator applied, then you can have enum members with the same value.

Wrapping Up

While I don’t think the enum module is really necessary for Python, it is a neat tool to have available. The documentation has a lot more examples and demonstrates other types of enums, so it is definitely worth a read.

Further Reading

PyDev of the Week: Elias Dorneles

This week we welcome Elias Dorneles as our PyDev of the Week! Elias works on the tooling of the Beeware Suite and contributes to several other projects too, all of which you can see on Github. He also has a programming blog that you can check out. Let’s take some time to learn more about Elias!

Can you tell us a little about yourself (hobbies, education, etc):

So, I was born and raised in the South of Brazil, and didn’t really have much access to computers until I was about 15 years old. I got into computers initially for writing music scores and making simple animations, spending several hours in the house of friends who owned a computer and shared similar interests. 🙂 Then, when I had the opportunity to go to the university I opted for Computer Science. In there I learned programming, started using Linux, got acquainted with the free and open source software culture and became more and more involved with it, little by little. My hobbies change from time to time, I like trying new things. Most consistently I play the guitar and make fingerstyle arrangements to pop songs that I can’t play myself. But you may also find me drawing cartoonish stuff, pair-programming with a friend over the internet, reading some book or just getting lost somewhere. I’ve recently moved to Paris, and since then I’ve been doing some traveling around too. Last year I took a sabbatical and attended the Recurse Center, which was a bit of a dream come true for me! There I met some wonderful people, worked a bit on the Android tooling of the BeeWare suite and practiced a lot of pair programming, it was a blast! Continue reading PyDev of the Week: Elias Dorneles

10 Years of Mouse Vs the Python

When I first started this blog, ten years ago today, I never thought I would be blogging about Python for a decade. In fact, the very first post wasn’t even about the Python language itself, but about me going to PyCon in Chicago. In fact, I wrote 7 articles about that first PyCon event before I wrote my very first tutorial-like article, which happened to be about reading OpenVPN’s status using wxPython and PyWin32.

Frankly this blog wouldn’t exist at all if there wasn’t a few readers that reached out to me to tell me how helpful the blog was or to put in article requests. Because of that encouragement, I continued writing and Python ended up being one of my passions. In fact, the continued encouragement and suggestions led me to writing my first book, Python 101, as well.

I don’t know if blogging will still be popular in another ten years, but if people continue to enjoy my content than I will continue to keep writing it. Thanks for all your support and happy coding!

Python 3: An Intro to f-strings

Python 3.6 added another way to do string interpolation that is called “f-strings” or Formatted string literals (PEP 498). The idea behind f-strings is to make string interpolation simpler. To create an f-string, you just need to prefix the string with the letter “f”. The string itself can be formatted in much the same way that you would with str.format(). In other words, you can have replacement fields in the string that are enclosed with curly braces. Here’s a simple example:

>>> name = 'Mike'
>>> f"Hello {name}"
'Hello Mike'

The Python documentation had a fun example that demonstrates how you can nest the replacement fields. I have modified it a bit to make it simpler though:

>>> total = 45.758
>>> width = 14
>>> precision = 4
>>> f"Your total is {total:{width}.{precision}}"
'Your total is          45.76'

Here we create three variables with the first one being a float and the other two being integers. Then we create our f-string and tell it that we want to put the total variable into our string. But you will note that within the string’s replacement field, we have nested the width and precision variables to format the total itself. In this case, we tell Python that we want the width of the total field to be 14 characters and the precision of the float to be 4, so the result is 45.76, which you will note is rounded up.

The f-string also supports date formatting:

>>> import datetime
>>> today =
>>> f"{today:%B %d, %Y}"
'March 13, 2018'

I personally like the example given in PEP 498 that actually shows how you can use the date formatting to extract the day of the week from the date:

>>> from datetime import datetime
>>> date = datetime(1992, 7, 4)
>>> f'{date} was on a {date:%A}'
'1992-07-04 00:00:00 was on a Saturday'

You can also use the same variable repeatedly in your f-string:

>>> spam = 'SPAM'
>>> f"Lovely {spam}! Wonderful {spam}!"
'Lovely SPAM! Wonderful SPAM!'

The documentation does note that you have to be careful with f-strings when nesting quotes. For example, you obviously can’t do something like this:

>>> value = 123
>>> f"Your value is "{value}""

This is a syntax error, just like it is when using a regular string. You also cannot use a backslash in your format string directly:

>>> f"newline: {ord('\n')}"
Traceback (most recent call last):
  Python Shell, prompt 29, line 1
Syntax Error: f-string expression part cannot include a backslash: <string>, line 1, pos 0

The documentation points out that you can put the backslash into a variable as a workaround though:

>>> newline = ord('\n')
>>> f"newline: {newline}"
'newline: 10'

In this example, we convert the newline character to its ordinal value. The last item that the documentation mentions is that you can’t use an f-string as a docstring. According to Nick Coghlan, this is because docstrings need to be known at compile time, but an f-string is not resolved until runtime.

Wrapping Up

At this point you should have enough information to start using f-strings in your own code. This is a fun addition to the Python language and while not strictly necessary, I can see it making string interpolation simpler in some aspects. Have fun and happy coding!

Further Reading

PyDev of the Week: Jason Myers

This week we welcome Jason Myers as our PyDev of the Week! Jason is the co-author of Essential SQLAlchemy: Mapping Python to Databases, 2nd Edition and is also an instructor at DataCamp. If you have some free time, check out which Python packages he contributes too over on Github or visit his website. Let’s take some time to get to know Jason!

Can you tell us a little about yourself (hobbies, education, etc):

I’m a software engineer, author, and instructor working for Juice Analytics, a data visualization company. I also started the PyTennessee and Nodevember conferences with my good friend Will Golden. This year, I’m serving as the program committee chair with Lorena Mesa and Jackie Kazil.

I was an infrastructure architect and consultant for the majority my computing career. When the cloud took over and stole all the beautiful blinking lights, I returned to programming full-time although I had always been writing code to solve infrastructure issues, configuration and monitoring.

For hobbies, I have three Lhasa Apso dogs and I grow corals in saltwater reef tanks. I find staring into the reef tanks very relaxing, and the chemistry involved satisfies my first love of analytical chemistry. Continue reading PyDev of the Week: Jason Myers

Python Interviews Excerpt: Sebastian Raschka

The following is an excerpt from my book, Python Interviews

Sebastian Raschka received his doctorate in Quantitative Biology and Biochemistry and Molecular Biology in 2017, from Michigan State University. Sebastian is the bestselling author of Python Machine Learning, which received the ACM Best of Computing award in 2016.

Driscoll: Python is one of the languages that is being used in AI and machine learning right now. Could you explain what makes it so popular?

Raschka: I think there are two main reasons, which are very related. The first reason is that Python is super easy to read and learn.

I would argue that most people working in machine learning and AI want to focus on trying out their ideas in the most convenient way possible. The focus is on research and applications, and programming is just a tool to get you there. The more comfortable a programming language is to learn, the lower the entry barrier is for more math and stats-oriented people.

Python is also super readable, which helps with keeping up-to-date with the status quo in machine learning and AI, for example when reading through code implementations of algorithms and ideas. Trying new ideas in AI and machine learning often requires implementing relatively sophisticated algorithms and the more transparent the language, the easier it is to debug.

The second main reason is that while Python is an easy language itself, we have a lot of great libraries on top of it that make our work easier. Nobody would like to spend their time on reimplementing basic algorithms from scratch (except in the context of studying machine learning and AI). The large number of Python libraries which exist, help us to focus on more exciting things than reinventing the wheel.

By the way, Python is also an excellent wrapper language for working with more efficient C/C++ implementations and CUDA/cuDNN, which is why existing machine learning and deep learning libraries run very efficiently in Python. This is also super important for working in the fields of machine learning and AI.

To summarize, I would say that Python is a great language that lets researchers and practitioners focus on machine learning and AI and provides less of a distraction than other languages.

Driscoll: So is Python just the right tool at the right time, or is there another reason that it’s become so important in AI and machine learning?

Raschka: I think that’s a bit of a chicken or the egg problem.

To untangle it, I would say that Python is convenient to use, which led to its wide adoption. The community has developed many useful packages in the context of scientific computing. Many machine learning and AI developers prefer Python as a general programming language for scientific computing and they have developed libraries on top of it, like Theano, MXNet, TensorFlow and PyTorch.

On an interesting side note, having been active in the machine learning and deep learning communities, there was one thing that I heard very often: “The Torch library is awesome, but it is written in Lua and I don’t want to spend my time learning yet another language.” Note that we have PyTorch now.

Read the rest interview in the book. You can get 40% off when purchasing from Packt’s website by using the following code: PIMD40. This code is good until March 16th, 2018.

PyDev of the Week: Alan Vezina

This week we welcome Alan Vezina (@fancysandwiches) as our PyDev of the Week! He is one of the co-founders of PuPPy (Puget Sound Programming Python), a Python user’s group in Seattle, WA. He is also one of the organizers of PyCascades, a Python conference in Vancouver, BC.  While Alan has a blog, it doesn’t appear to be updated regularly so you might want to check out his Github profile instead to find out what he’s been up to. Now let’s take a few moments to get to know him better!

Can you tell us a little about yourself (hobbies, education, etc):

Born and raised in the midwest, but have been living in Seattle for the past 6 years. I have a Bachelors in Computer Science from University of Michigan. I am an avid cyclist, I commute to work by bike year round (Seattle makes that easy), and I don’t own a car. I’ve been experimenting a lot with homebrewing fruit wines and mead lately. Continue reading PyDev of the Week: Alan Vezina

Python Interviews Book Released!

My Python Interviews book is now officially released! In it you will find 20 interviews with Python experts from a diverse set of fields.

I also have a special code from Packt that will take 40% off the eBook for up to 1000 readers. Just apply the following code when you are checking out: PIMD40. This code is good until March 16th, 2018.

Note: The book is only available at Packt currently, but will be available on Amazon and other retail locations on March 9th, 2018.

Packt has a history of donating to open source projects and would like to make a donation to the Python Software Foundation from this book. So, for every copy Packt sells in March they will make a donation to the PSF on both their own e-commerce website and via the discount code for Amazon. The Amazon discount code is 30PYTHON (This code might not work until March 9th)

Python 3.7 – Dictionaries now ordered

One of my readers pointed out to me that Python 3.7 will now have ordered dictionaries by default. You can read the “announcement” over on the Python-Dev list.

Python’s dict has always been unordered up until Python 3.6, when it was changed to be ordered based on a proposal by Raymond Hettinger, who is one of Python’s core developers.

The release notes for Python 3.6 said the following:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

Now when Python 3.7 is released, the ordered implementation of the dict will be the standard. I think this is pretty neat.

PyDev of the Week: David Litvak

This week we welcome David Litvak (@dlitvakb) as our PyDev of the Week! He has presented at PyCon Argentina and PyCaribbean. Feel free to check out his website or Github to see what he’s been up to. Now let’s take some time to learn more about David!

Can you tell us a little about yourself (hobbies, education, etc):

My name is David Litvak Bruno, a Software Developer and Systems Analyst from Buenos Aires, Argentina, and now living in Berlin, Germany. I’m currently working as an Ecosystem Developer and Python and Ruby Software Evangelist at Contentful in Berlin, Germany.

I’ve been working as a Software Engineer since 2007, just before I started my studies at UTN (National Technological University) for Systems Engineering, which after a few years of dealing between a full time job and lack of enthusiasm with the university, I ended up leaving. Though during those years I started my teaching career in Advanced Programming Techniques and Team Leadership Methodologies, which I still continue to contribute at remotely.

I eventually finished my degree as a Systems Analyst in UP (Palermo University), in February 2017.

My hobbies are very varied, from listening and ocasionally performing with some jazz bands, to combat sports such as MMA and HEMA. I also love teaching and playing Tabletop Role Playing Games.

On October, I moved from Buenos Aires to Berlin, and I’m thoroughly enjoying it.

Just a few weeks ago I became a father, Julián is now the receiver of my full attention. Continue reading PyDev of the Week: David Litvak