Outils pour utilisateurs

Outils du site


issue147:python

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.

Comme vous pouvez le savoir, Python 3.8.0b2 a été publié le 4 juillet. Il est disponible pour téléchargement sur https://www.python.org/downloads/release/python-380b2/. Pour Linux, il n'y a pas de binaires disponibles ; aussi, vous devrez le compiler vous-même.

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.

Il y a beaucoup de modifications dans la version 3.8.0 et nous avons déjà vu l'une d'elles en avril (FCM n° 144). Les arguments « positional-only ». Beaucoup ont trait à CPython et d'autres choses dont certains d'entre vous n'auront jamais à se soucier. Voici une liste de quelques autres points nouveaux : ••Expressions d'affectation - PEP 572 (voir ci-dessous) ••Protocole 5 de Pickle avec des données « out-of-band » - PEP 574 ••Absence d'audit dans le runtime - PEP 578 ••Support pratique des f-strings = spécifieur pour le débogage (voir ci-dessous) ••LOAD_GLOBAL est maintenant 40 % plus rapide ••pickle utilise maintenant le protocole 4 par défaut ••En lien avec la saisie : PEP 591 (Qualifieur final), PEP 586 (Type de literal) PEP 589 (TypedDict)

Je vais me concentrer sur deux types de modification dans cet article. D'abord, nous regarderons la modification de l'expression d'affectation.

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.

Dans cette modification, nous y trouvons un opérateur supplémentaire. Il est appelé « opérateur walrus » (morse). Il est codé ainsi : « := » (tournez votre tête à gauche et vous verrez pourquoi il est appelé « morse »). Il nous permet d'assigner une valeur à une variable faisant partie d'une expression. À première vue, ça ressemble à ce que nous avons déjà. Mais, attendez ! Voici comment il fonctionne :

Partons de l'idée que nous avons une liste. Nous l'appelons « lst ». Elle a 12 éléments. Présumons aussi que nous voulons vérifier si le nombre d'éléments est supérieur, disons, à 10. Plutôt facile, n'est-ce pas ? Voici la méthode ancienne (avant la 3.8.0) : n = len(lst)

if n > 10 :

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

Maintenant, nous utiliserons le nouvel opérateur walrus. Souvenez-vous que l'on doit avoir Python 3.8.0 pour lancer ce code :

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

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

Vous voyez ; nous avons gagné une ligne de 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

Voyez ci-dessus un autre exemple, un peu plus « monde réel ».

Ici, nous importons une bibliothèque json et créons une chaîne compatible avec json contenant un certain nombre d'entrées de villes/États, latitude et longitude. Ensuite, nous utilisons la méthode de chargement de chaîne json.loads en l'assignant à une variable appelée « locations » (emplacements). Puis, nous obtenons la liste des entrées dans la variable « l ».

l = locations[“locations”]

Ensuite (page suivante, en haut à droite), nous parcourons la liste, une entrée à la fois, et nous utilisons l'opérateur walrus pour vérifier si l'entrée « City » (ville) commence avec le nom « Odessa ». Si c'est le cas, nous imprimons la nouvelle variable « city », la latitude et la longitude. Autrement, nous ignorons les données.

La sortie de ce court programme serait :

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))

L'autre nouveau point dont j'aimerais parler a trait à un ajout dans le format des f-strings. C'est en gros une aide pour l'utilisation de l'impression quand vous déboguez votre code. Les f-strings ont été introduites dans Python 3.6 et elles sont la troisième option de formatage des chaînes avec l'option de formatage « format % » (qui ne date pas d'hier) et l'option « str.format() » qui date de python 2.6.

Je pars du principe que vous comprenez tous l'option de format %, je travaille avec depuis mes premiers articles. Je suis sûr que la plupart d'entre vous utilisez aussi l'option str.format(), mais, juste au cas où, voici un rappel rapide.

Disons que vous voulez créer une chaîne pour l'impression qui comprend les variables de données suivantes :

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

Dans la méthodologie de format %, vous utiliserions :

print(“Écrit pour %s numéro #%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))

Ce qui produit :

Écrit pour Full Circle Magazine numéro #147 July, 2019

Pour utiliser la méthode str.format(), nous le coderions ainsi :

print('Écrit pour {} numéro #{} {}, {}'.format(mag, issue, month, year))

qui fournit la même sortie. Notez que les accolades tiennent lieu de points de placement pour les variables de la portion de la déclaration .format(). Quand les accolades sont utilisées, vous pouvez, soit laisser vide (comme ci-dessus), soit fournir un nombre « index » qui est lié à l'index d'une déclaration de format comme celle-ci :

print('Écrit pour {0} numéro #{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.

Encore une fois, cela produit la même sortie que les autres. Encore une façon différente de faire dans ce qui suit :

print('Écrit pour {mag} numéro #{issue} {month}, {year}'.format(mag=mag, issue=issue, month=month, year=year))

Cependant, ceci est un peu pataud, et comme vous pouvez le voir, rend longue la déclaration quand plusieurs variables/emplacements sont utilisés. Dans un cas comme celui-ci, on doit écrire un code de débogage plus long que nécessaire.

Maintenant, utilisons les f-strings. L'idée reste la même que pour str.format(), mais la raccourcit considérablement. Ça la rend aussi beaucoup plus lisible.

print(f“Écrit pour {mag} numéro #{issue} {month}, {year}”)

Comme vous pouvez le voir, c'est plus court (et lisible), car nous plaçons simplement un « f » avant les guillemets ouvrants et utilisons les noms de variables dans des accolades, oubliant la portion du « .format() ».

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.

Maintenant, pour la partie nouvelle, Python 3.8 nous donne la possibilité d'utiliser un signe « = ». Comme je l'ai dit plus haut, c'est surtout une aide pour le débogage. Présumant les affectations de variable ci-dessus, si nous voulons imprimer la valeur de la variable mag, nous pouvons simplement faire ceci :

print(mag)

Et, comme nous le savons tous, ça imprimera :

Full Circle Magazine

Mais, si nous utilisons la nouvelle option = fournie par Python 3.8, nous pouvons utiliser ce qui suit :

print(f“{mag=}”)

Cela affichera :

mag='Full Circle Magazine'

C'est tellement plus facile à lire en sortie de débogage sur le terminal que la seule sortie précédente.

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!

Il y a tant de choses nouvelles qui nous sont proposées par Python 3.8. Alors que la compilation de Python par vous-même peut s'avérer délicate, il y a beaucoup de sites Web qui offrent des instructions pas-à-pas pour le faire. Toutefois, souvenez-vous que c'est un produit en bêta, il peut donc y avoir des problèmes. Vous pourriez vouloir attendre quelques mois jusqu'à ce qu'une des RC (Release candidate - pré-version publiée) devienne disponible. Ce peut être aussi une excellente idée de créer vous-même une sorte d'environnement virtuel pour vous assister dans votre travail avec la 3.8 sans risquer de casser quoi que ce soit de ce que vous avez actuellement. Voyez-le comme un bac à sable.

Pour une liste détaillée des fonctionnalités qui arrivent dans Python 3.8, voyez https://docs.python.org/3.8/whatsnew/3.8.htmlhttps://docs.python.org/3.8/whatsnew/3.8.html

La publication de Python 3.8.0 est actuellement prévue le 21/10/19.

Jusqu'au prochain numéro, amusez-vous à coder !

issue147/python.txt · Dernière modification : 2019/08/08 10:21 de andre_domenech