What is new in Python 3.9
Haim Michael
March 8th
, 2021
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
life
michae
l
Let's be on The Edge
www.lifemichael.com
© 2008 Haim Michael 20150805
Python 3.9
© 2008 Haim Michael 20150805
The dict Union | Operator
 The dict union operator | return a new dict consisting of the
left operand merged with the right operand, each of which
must be a dict (or an instance of a dict subclass).
 When the key appears in both operands, the last-seen value
(i.e. that from the right-hand operand) wins.
https://www.python.org/dev/peps/pep-0584/
© 2008 Haim Michael 20150805
The dict Union | Operator
dict1 = {1:'one', 2:'two', 3:'three'}
dict2 = {3:'three',4:'four',5:'five',6:'six'}
dict3 = dict1 | dict2
print(dict3)
© 2008 Haim Michael 20150805
Type Hinting Generics in Collections
 We can now use the generics syntax when using the standard
collections in Python. We are no longer limited to using
generics with the collections the typing module includes.
 As of Python 3.9 we no longer need the standard collections
the typing module includes.
https://www.python.org/dev/peps/pep-0585/
© 2008 Haim Michael 20150805
Type Hinting Generics in Collections
numbers: list[int] = [23, 3, 6]
student: tuple[str, str, float, int] = ("mosh", "solomon", 98.2, 2343243)
nicknames: dict[str, str] = {"mosh": "moshe", "tal": "talia", "avi": "avraham"}
winners: set[str] = {"dave", "mark", "tal", "doron", "jane"}
print(numbers)
print(student)
print(nicknames)
print(winners)
© 2008 Haim Michael 20150805
The Prefix and Suffix Methods
 The methods, removeprefix() and removesuffix(), are
now available when using Python's various string objects.
 These methods would remove a prefix or suffix (respectively)
from a string, if present.
 These two methods will be available when using objects of the
types str, bytes, bytearray and collections.UserString.
https://www.python.org/dev/peps/pep-0616/
© 2008 Haim Michael 20150805
The Prefix and Suffix Methods
filenames:list[str] = [
"king.txt.txt",
"temp.txt",
"pep8song.txt",
"data.txt"]
for filename in filenames:
if filename.endswith(".txt.txt"):
print(filename.removesuffix(".txt"))
else:
print(filename)
© 2008 Haim Michael 20150805
The Prefix and Suffix Methods
names: list[str] = ["Dr.Mosh Levin", "Dr.Ronan Cohen", "Ran Roze"]
for name in names:
if name.startswith("Dr."):
print(name.removeprefix("Dr."))
else:
print(name)
© 2008 Haim Michael 20150805
Annotated Type Hints
 The possibility to annotate a function allows us to add
arbitrary metadata to functions we define.
def calc(distance: "meter", time: "second") -> "km per hour":
return 3600 * (distance / 1000) / time
 As of Python 3.9 we can use the typing.Annotated
from typing import Annotated
def calc(
distance: Annotated[int, "meter"],
time: Annotated[float, "second"]
) -> Annotated[float, "km per hour"]:
return 3600 * (distance / 1000) / time
© 2008 Haim Michael 20150805
Annotated Type Hints
 We can (as usual) access the annotations through
the .__annotations__ attribute.
from typing import Annotated
def calc(
distance: Annotated[int, "meter"],
time: Annotated[float, "second"]
) -> Annotated[float, "km per hour"]:
return 3600 * (distance / 1000) / time
print(calc.__annotations__)
© 2008 Haim Michael 20150805
Annotated Type Hints
 We can keep our code more readable by using type
aliases.
from typing import Annotated
Meter = Annotated[int, "meter"]
Second = Annotated[int, "second"]
KmPerHour = Annotated[float, "km per hour"]
def calc(distance: Meter, time: Second) -> KmPerHour:
return 3600 * (distance / 1000) / time
print(calc.__annotations__)
© 2008 Haim Michael 20150805
Powerful Parser
 One of the main components of the Python interpreter
is the parser.
 As of Python 3.9, we have a new parser. The new
parser was developed based on Guido's research of
PEG (Parsing Expression Grammar) parsers.
© 2008 Haim Michael 20150805
Powerful Parser
 The interpreter (in Python 3.9) includes both the new
PEG parser and the old LL(1) parser. The PEG parser
is the default one. It is still possible to use the LL(1) old
one by using the -X oldparser command-line flag:
$ python -X oldparser program.py
© 2008 Haim Michael 20150805
Powerful Parser
 The old parser will be removed in Python 3.10. This will
allow the implementation of new features without the
limitations of an LL(1) grammar (e.g. implementing
structural pattern matching).
 The performance of both parsers, the PEG parser and
the LL(1) parser, is similar.
© 2008 Haim Michael 20150805
The graphlib Module
 As of Python 3.9, the standard library includes the
graphlib new module.
from graphlib import TopologicalSorter
dependencies = {
"Java EE": {"Java", "Angular"},
"Angular": {"JavaScript"},
"Java": {"C++", "SQL"},
"C++": {"C"}
}
sorter = TopologicalSorter(dependencies)
print(list(sorter.static_order()))
© 2008 Haim Michael 20150805
The Least Common Multiple(LCM)
 As of Python 3.9, we can easily find the least common
multiple (LCM) by calling the math.lcm function.
import math
num1 = 5
num2 = 7
num3 = 3
result = math.lcm(num1,num2,num3)
print(result)
© 2008 Haim Michael 20150805
HTTP Status Codes
 As of Python 3.9, the http module includes two more
status codes: 103 (Early Hints) and 425 (Too Early).
from http import HTTPStatus
print(HTTPStatus.OK)
print(HTTPStatus.OK.description)
print(HTTPStatus.OK.value)
print(HTTPStatus.OK.phrase)
print(HTTPStatus.NOT_FOUND)
print(HTTPStatus.NOT_FOUND.description)
print(HTTPStatus.NOT_FOUND.value)
print(HTTPStatus.NOT_FOUND.phrase)
print(HTTPStatus.EARLY_HINTS)
print(HTTPStatus.TOO_EARLY)
© 2008 Haim Michael 20150805
The zoneinfo Module
 The zoneinfo was added in Python 3.9. It
complements the datetime module by allowing us
getting information about the time zone.
from datetime import datetime
from zoneinfo import ZoneInfo
vancouver = ZoneInfo("America/Vancouver")
release = datetime(2020, 11, 25, 2, 12, tzinfo=vancouver)
print(release)
© 2008 Haim Michael 20150805
The zoneinfo Module
 The following code sample prints out the available time
zones.
import zoneinfo
zones = zoneinfo.available_timezones()
print(len(zones))
print(zones)
© 2009 Haim Michael All Rights Reserved 21
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
+972+54+6655837 (whatsapp)
life
michael

What is new in Python 3.9

  • 1.
    What is newin Python 3.9 Haim Michael March 8th , 2021 All logos, trade marks and brand names used in this presentation belong to the respective owners. life michae l Let's be on The Edge www.lifemichael.com
  • 2.
    © 2008 HaimMichael 20150805 Python 3.9
  • 3.
    © 2008 HaimMichael 20150805 The dict Union | Operator  The dict union operator | return a new dict consisting of the left operand merged with the right operand, each of which must be a dict (or an instance of a dict subclass).  When the key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins. https://www.python.org/dev/peps/pep-0584/
  • 4.
    © 2008 HaimMichael 20150805 The dict Union | Operator dict1 = {1:'one', 2:'two', 3:'three'} dict2 = {3:'three',4:'four',5:'five',6:'six'} dict3 = dict1 | dict2 print(dict3)
  • 5.
    © 2008 HaimMichael 20150805 Type Hinting Generics in Collections  We can now use the generics syntax when using the standard collections in Python. We are no longer limited to using generics with the collections the typing module includes.  As of Python 3.9 we no longer need the standard collections the typing module includes. https://www.python.org/dev/peps/pep-0585/
  • 6.
    © 2008 HaimMichael 20150805 Type Hinting Generics in Collections numbers: list[int] = [23, 3, 6] student: tuple[str, str, float, int] = ("mosh", "solomon", 98.2, 2343243) nicknames: dict[str, str] = {"mosh": "moshe", "tal": "talia", "avi": "avraham"} winners: set[str] = {"dave", "mark", "tal", "doron", "jane"} print(numbers) print(student) print(nicknames) print(winners)
  • 7.
    © 2008 HaimMichael 20150805 The Prefix and Suffix Methods  The methods, removeprefix() and removesuffix(), are now available when using Python's various string objects.  These methods would remove a prefix or suffix (respectively) from a string, if present.  These two methods will be available when using objects of the types str, bytes, bytearray and collections.UserString. https://www.python.org/dev/peps/pep-0616/
  • 8.
    © 2008 HaimMichael 20150805 The Prefix and Suffix Methods filenames:list[str] = [ "king.txt.txt", "temp.txt", "pep8song.txt", "data.txt"] for filename in filenames: if filename.endswith(".txt.txt"): print(filename.removesuffix(".txt")) else: print(filename)
  • 9.
    © 2008 HaimMichael 20150805 The Prefix and Suffix Methods names: list[str] = ["Dr.Mosh Levin", "Dr.Ronan Cohen", "Ran Roze"] for name in names: if name.startswith("Dr."): print(name.removeprefix("Dr.")) else: print(name)
  • 10.
    © 2008 HaimMichael 20150805 Annotated Type Hints  The possibility to annotate a function allows us to add arbitrary metadata to functions we define. def calc(distance: "meter", time: "second") -> "km per hour": return 3600 * (distance / 1000) / time  As of Python 3.9 we can use the typing.Annotated from typing import Annotated def calc( distance: Annotated[int, "meter"], time: Annotated[float, "second"] ) -> Annotated[float, "km per hour"]: return 3600 * (distance / 1000) / time
  • 11.
    © 2008 HaimMichael 20150805 Annotated Type Hints  We can (as usual) access the annotations through the .__annotations__ attribute. from typing import Annotated def calc( distance: Annotated[int, "meter"], time: Annotated[float, "second"] ) -> Annotated[float, "km per hour"]: return 3600 * (distance / 1000) / time print(calc.__annotations__)
  • 12.
    © 2008 HaimMichael 20150805 Annotated Type Hints  We can keep our code more readable by using type aliases. from typing import Annotated Meter = Annotated[int, "meter"] Second = Annotated[int, "second"] KmPerHour = Annotated[float, "km per hour"] def calc(distance: Meter, time: Second) -> KmPerHour: return 3600 * (distance / 1000) / time print(calc.__annotations__)
  • 13.
    © 2008 HaimMichael 20150805 Powerful Parser  One of the main components of the Python interpreter is the parser.  As of Python 3.9, we have a new parser. The new parser was developed based on Guido's research of PEG (Parsing Expression Grammar) parsers.
  • 14.
    © 2008 HaimMichael 20150805 Powerful Parser  The interpreter (in Python 3.9) includes both the new PEG parser and the old LL(1) parser. The PEG parser is the default one. It is still possible to use the LL(1) old one by using the -X oldparser command-line flag: $ python -X oldparser program.py
  • 15.
    © 2008 HaimMichael 20150805 Powerful Parser  The old parser will be removed in Python 3.10. This will allow the implementation of new features without the limitations of an LL(1) grammar (e.g. implementing structural pattern matching).  The performance of both parsers, the PEG parser and the LL(1) parser, is similar.
  • 16.
    © 2008 HaimMichael 20150805 The graphlib Module  As of Python 3.9, the standard library includes the graphlib new module. from graphlib import TopologicalSorter dependencies = { "Java EE": {"Java", "Angular"}, "Angular": {"JavaScript"}, "Java": {"C++", "SQL"}, "C++": {"C"} } sorter = TopologicalSorter(dependencies) print(list(sorter.static_order()))
  • 17.
    © 2008 HaimMichael 20150805 The Least Common Multiple(LCM)  As of Python 3.9, we can easily find the least common multiple (LCM) by calling the math.lcm function. import math num1 = 5 num2 = 7 num3 = 3 result = math.lcm(num1,num2,num3) print(result)
  • 18.
    © 2008 HaimMichael 20150805 HTTP Status Codes  As of Python 3.9, the http module includes two more status codes: 103 (Early Hints) and 425 (Too Early). from http import HTTPStatus print(HTTPStatus.OK) print(HTTPStatus.OK.description) print(HTTPStatus.OK.value) print(HTTPStatus.OK.phrase) print(HTTPStatus.NOT_FOUND) print(HTTPStatus.NOT_FOUND.description) print(HTTPStatus.NOT_FOUND.value) print(HTTPStatus.NOT_FOUND.phrase) print(HTTPStatus.EARLY_HINTS) print(HTTPStatus.TOO_EARLY)
  • 19.
    © 2008 HaimMichael 20150805 The zoneinfo Module  The zoneinfo was added in Python 3.9. It complements the datetime module by allowing us getting information about the time zone. from datetime import datetime from zoneinfo import ZoneInfo vancouver = ZoneInfo("America/Vancouver") release = datetime(2020, 11, 25, 2, 12, tzinfo=vancouver) print(release)
  • 20.
    © 2008 HaimMichael 20150805 The zoneinfo Module  The following code sample prints out the available time zones. import zoneinfo zones = zoneinfo.available_timezones() print(len(zones)) print(zones)
  • 21.
    © 2009 HaimMichael All Rights Reserved 21 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 +972+54+6655837 (whatsapp) life michael