Outils pour utilisateurs

Outils du site


issue147:python

Ceci est une ancienne révision du document !


As some of you may know, Python 3.8.0b2 was released on July the fourth. It is available for download at https://www.python.org/downloads/release/python-380b2/. For Linux, there are no binaries available, so you must compile it yourself.

There are a lot of changes in version 3.8.0, one of which we have already looked into back in April (FCM #144), Positional-only arguments. Many have to do with CPython and things that some of us won’t ever need to worry about. Here is a list of a few of the other things that are new: • Assignment Expressions - PEP 572 (see below) • Pickle protocol 5 with out-of-band data - PEP 574 • Runtime audit hooks - PEP 587 • f-strings support handy = specifier for debugging (see below) • LOAD_GLOBAL is now 40% faster • pickle will now use Protocol 4 by default • Typing-related: PEP 591 (Final qualifier), PEP 586 (Literal type) PEP 589 (TypedDict)

I'm going to focus on two of the changes in this article. First, we'll take a look at the Assignment Expression change.

In this change, there is an additional operator for us. It's called the “walrus operator”. It's coded as “:=” (turn your head to the left and you'll see why it's called “walrus”). This allows us to assign a value to a variable as part of an expression. At first glance that sounds like what we already have. But wait! Here is how it works…

Assume we have a list. We'll call it “lst”. It has 12 items. Let's further assume that we want to check to see if the number of items is greater than, let's say 10. Easy enough, right? Here is the old way (pre 3.8.0)…

n = len(lst)

if n > 10 :

  print('List is too big.  {0} items found, expected 10.'.format(n))

Now, we'll use the new walrus operator. Remember, you need to have Python 3.8.0 in order to run this code…

if (n := len(lst)) > 10:

  print('List is too big.  {0} items found, expected 10.'.format(n))

You can see that it saves us a line of code.

Here (top) is another example, a bit more “real world”.

Here we import the json library and create a string compliant with json containing a number of city/state, latitude and longitude entries. We then use the json.loads load string method assigning it to a variable called locations. We then get the list of entries into the variable 'l'.

l = locations[“locations”]

Next (next page, top right) we step through the list, one at a time, and use the new walrus operator to check to see if the “City” entry starts with the name “Odessa”. If so, we print the new variable city, the latitude and longitude. Otherwise, we ignore the data.

The output from this short program would be…

Odessa, Texas, USA 31.84 -102.36

The other new item I wanted to discuss deals with the f-strings formatting addition. It’s basically an aid for using print when debugging your code. F-strings were introduced in Python 3.6 and is the third formatting option for strings along with the “% formatting” option (which goes WAY back) and the “str.format()” option which goes back to Python 2.6.

I assume you all understand the % formatting option – I’ve dealt with it since my first few articles. I’m sure most of you have used the str.format() option as well, but just in case, here is a quick recap.

Let’s say that you want to create a string for printing that includes the following data variables…

mag = “Full Circle Magazine” issue = “147” month = “July” year = “2019”

In the % formatting methodology, you would use…

print(“Written for %s issue #%s %s, %s” %(mag,issue,month,year))

Which would produce:

Written for Full Circle Magazine issue #147 July, 2019

To use the str.format() method, you would code it like this:

print('Written for {} issue #{} {}, {}'.format(mag, issue, month, year))

Which provides the same output. Notice that the curly brackets act as place holders for the variables in the .format() portion of the statement. When using the curly brackets, you can either leave them empty (as above) or provide an “index” number which relates to the index within the format statement like this…

print('Written for {0} issue #{1} {2}, {3}'.format(mag, issue, month, year))

Again, this produces the same output as the others. Yet another way to do this is to do the following:

print('Written for {mag} issue #{issue} {month}, {year}'.format(mag=mag, issue=issue, month=month, year=year))

This, however, is somewhat clumsy and, as you can see, makes the statement long when multiple variable/replacements are used. In a case like this, it makes writing the debug code longer than it needs to be.

Now to using f-strings. The idea is similar to the str.format, but shortens it considerably. It also makes it much more readable.

print(f“Written for {mag} issue #{issue} {month}, {year}”)

As you can see, it is much shorter (and readable), since we simply place an “f” before the opening quote and use the variable names within the curly brackets, forgetting about the ‘.format()’ porton.

Now for the new part. Python 3.8 gives us the ability of using an ‘=’ sign. As I said above, this is mainly for debugging support. Assuming the variable assignments above, if we want to print the value of the mag variable, we could simply do it like this…

print(mag)

And as we all know, will print…

Full Circle Magazine

But if we use the new = option provided to us by Python 3.8, we can use the following…

print(f“{mag=}”)

This will display:

mag='Full Circle Magazine'

This is so much easier to read in the debugging output in the terminal than just the previous output.

There are so many new things that Python 3.8 offers us. While compiling Python on your own can be a challenge, there are many websites that offer step-by-step instructions to do this. Remember, however, this is a beta product, so there are bound to be issues. You might want to wait a few months until one of the release candidates become available. It would also be a good idea to create yourself some sort of virtual environment to support your 3.8 work without risking breaking anything you currently have. Consider it a “sandbox”.

For a detailed list of the upcoming features in Python 3.8.0, see https://docs.python.org/3.8/whatsnew/3.8.htmlhttps://docs.python.org/3.8/whatsnew/3.8.html

Python 3.8.0 is currently expected to be released on 10/21/19.

Until next time, happy coding!

issue147/python.1564435292.txt.gz · Dernière modification : 2019/07/29 23:21 de d52fr