What’s New in Python 3.6 ?
Malini Shukla
Senior Data Scientist || Hiring || 6M+ impressions || Trainer || Top Data Scientist || Speaker || Top content creator on LinkedIn || Tech Evangelist
What’s new in Python 3.6?
We know that the future belongs to Python 3.x. But we have a number of versions in Python 3000. For example, Python 3.3.3 and Python 3.4.3. The latest version of Python is 3.6. So, let’s see what’s new in Python 3.6 and how it is different from older versions, Python 3.6 performance and features.
New Syntax Features of Python 3.6
With Python 3.6, we see some new syntax features. Let’s take a look.
a. PEP 498 (Formatted String Literals)
You guessed it right. PEP 498 introduces f-strings.
An f-string is a string that you can format to put values inside it. For this, we precede the string with an ‘f’ or an ‘F’. We mention the variables inside curly braces.
- >>> hometown,city='Ahmedabad','Indore'
- >>> print(f"I love {hometown}, but I live in {city}")
I love Ahmedabad, but I live in Indore
For more on f-strings, read Python Strings.
b. PEP 526 (Syntax for Variable Annotations)
PEP 484 standardizes type annotations for function parameters. We also call these type hints.
- >>> class A:
- name:str
- >>> A.__annotations__
- {'name': <class 'str'>}
Annotations do not pose meaning to the interpreter, and are of use to third-party tools and libraries.
c. PEP 515 (Underscores in Numeric Literals)
With PEP 515, we can use underscores in numeric literals- between digits and after base specifiers.
- >>> 0x_FF_FE_FF_FE
4294901758
d. PEP 525 (Asynchronous Generators)
PEP 492 introduced native coroutines and async/await syntax. Unlike Python 3.5, Python 3.6 can have await and yield in the same function body. So, we can define asynchronous generators:
- >>> async def ticker(delay, to):
- """Yield numbers from 0 to *to* every *delay* seconds."""
- for i in range(to):
- yield i
- await asyncio.sleep(delay)
This makes code faster and more concise.
e. PEP 530 (Asynchronous Comprehensions)
With PEP 530, you can use async for in lists, sets, dict comprehensions, and generator expressions.
result = [i async for i in aiter() if i % 2]
f. PEP 487 (Simpler Customization of Class Creation)
Now, we don’t need a metaclass to customize subclass creation. Whenever we create a new subclass, it calls the __init_subclass__ classmethod.
- class PluginBase:
- subclasses = []
- def __init_subclass__(cls, **kwargs):
- super().__init_subclass__(**kwargs)
- cls.subclasses.append(cls)
- class Plugin1(PluginBase): pass
- class Plugin2(PluginBase): pass
g. PEP 495 (Local Time Disambiguation)
PEP 495 introduces the ‘fold’ attribute to instances of the datetime.datetime and datetime.time classes. This way, it can differentiate between two moments in time with the same local times.
h. PEP 529 (Change Windows filesystem encoding to UTF-8)
With Python 3.6, no data loss occurs when we use bytes paths on Windows.
i. PEP 528 (Change Windows console encoding to UTF-8)
Now, the default console on Windows accepts all Unicode characters. It also provides correctly-read str objects to Python code. Now, sys.stdin, sys.stdout, and sys.stderr default to utf-8 encoding.
j. PEP 520 (Preserving Class Attribute Definition Order)
With PEP 520, the natural ordering of attributes in a class is preserved in the class’ __dict__ attribute. Now, the default effective class ‘execution’ namespace is an insertion-order-preserving mapping.
k. PEP 468 (Preserving Keyword Argument Order)
Python now guarantees that **kwargs in a function signature is an insertion-order-preserving mapping.
l. PEP 523 (Adding a frame evaluation API to CPython)
PEP 523 introduces an API to make frame evaluation pluggable at the C level. This way, tools like debuggers and JITs can intercept frame evaluation before the Python code even begins to execute.
These are the Python 3.6 new feature syntax.
Read:13 Unique Features of Python Programming Language
Other Additions in Python 3.6
- The PYTHONMALLOC environment variable allows us to set the Python memory allocators and install debug hooks.
- New dict implementation- Now, dict() uses between 20% and 25% less memory compared to Python 3.5.
- Earlier, it would give you a SyntaxWarning if you did not use a ‘global’ or ‘nonlocal’ statement before the first use of the affected name in that scope.
- Now, Import raises the new exception ModuleNotFoundError, which is a subclass of ImportError. Code that checks for ImportError still works.
- The interpreter now abbreviates long sequences of repeated traceback lines as “[Previous line repeated {count} more times]”.
- Class methods that rely on zero-argument super() now work perfectly when we call them from metaclass methods at class creation.
- Now, we can set a special method to None when we want to indicate that the operation is unavailable. For instance, a class that sets __iter__() to None isn’t iterable.
The is some this what’s extremely new in Python 3.6.
New Modules in Python 3.6
a. secrets
Python 3.6 introduces a new module, ‘secrets’. This module lends us a way to reliably generate cryptographically strong pseudo-random values. Using these, we can manage secrets like account authentication, tokens, and so.
Any doubt yet in What’s new in Python 3.6 tutorial because now there is a long list of Improved modules. Also refer this article on Python Modules vs Packages.
Improved Python 3.6 Modules
Why stop at what we have, when we can tweak it into something even more awesome? Python 3.6 makes the following improvements:
- array – Now, exhausted iterators of array.array stay exhausted even when the iterated array extends. This is in consistence with other mutable sequences’ behavior.
- ast – Python adds the new ast.Constant AST node. External AST optimizers use them for constant folding.
- asyncio – With Python 3.6, the asyncio module is no longer provisional; its API is now stable.
- binascii – Now, the function b2a_base64() accepts an optional newline keyword. This way, it can control whether the newline character appends to the return value.
- cmath – Python 3.6 added a new constant cmath.tau(τ).