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 = datetime.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

ReportLab Book Kickstarter’s – 2 Days Left

There is only a little over 2 days left for my ReportLab book Kickstarter. This is your only chance to purchase a signed copy of the book and it’s also probably the cheapest way of getting the eBooks too!

I currently have 7 chapters done with number 8 nearing completion. There are over 170 pages in these chapters alone. I hope you’ll check it out as ReportLab is a fun way to use Python to design dynamic reports in a PDF format.

PyDev of the Week: Juan Luis Cano

This week we welcome Juan Luis Cano (@astrojuanlu) as our PyDev of the Week! He is the chair of the Python Spain non-profit and the author of the poliastro project. If you can read Spanish, then you might want to check out his website. Otherwise you can definitely take a look at his Github profile to see what he’s been working on or is interested in. Let’s take some time to learn more about Juan!

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

I’m an Aerospace engineer with a passion for space, programming and open source. I really enjoy solving Physics or Math problems using computers, and the more my job requires me reading scientific papers and derive mathematical equations, the happier I am. I am an open culture advocate and also chair of the Python Spain non-profit, which organizes the PyCon in our country (I have been involved one way or another since the first edition, in 2013). When I am not in front of the computer, I love to listen to all kinds of music (electronic, ’70s rock, opera, blues), go everywhere with my bicycle and travel.

Continue reading PyDev of the Week: Juan Luis Cano