What’s New in Python 3.6 ? | New Features in Python 3.6

Free Python courses with 57 real-time projects - Learn Python

1. Python 3.6 Tutorial

In this article on Python 3.6, we will discuss the following new features in Python 3.6. Moreover, we will discuss

  • New Syntax Features of Python 3.6
  • New Modules in Python 3.6
  • Improved Python 3.6 Modules

So, let’s start the Python 3.6 Tutorial.

What's New in Python 3.6 ? | New Features in Python 3.6

What’s New in Python 3.6? | New Features in Python 3.6

2. 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.

3. 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

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

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

4. 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.

5. 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.

What's New in Python 3.6 ? | New Features in Python 3.6

What’s new in python 3.6 – Secrets

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.

6. 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(τ).
>>> from cmath import tau
>>> tau

6.283185307179586

  • collections – Here’s all that is new in the ‘collections’ module:

Collection ABC- to represent sized iterable container classes.

Reversible ABC- to represent iterable classes. These also provide the method __reversed__().

AsyncGenerator ABC- to represent asynchronous generators.

Other than these, the namedtuple() function will now accept an optional keyword argument ‘module’. Now, the arguments ‘verbose’ and ‘rename’ for namedtuple() are keyword-only. Finally, we can now pickle recursive collections.deque instances.

  • concurrent.futures – Now, the class constructor ThreadPoolExecutor accepts an optional thread_name_prefix argument. This lets us customize thread names for the thread created by the pool.
  • contextlib – The new contextlib.AbstractContextManager class provides an ABC for context managers. This provides a sensible default implementation for __enter__().
  •  datetime – Python 3.6 has a fold attribute for the datetime and time classes. This disambiguates local time.

The function datetime.isoformat() takes an optional argument ‘timespec’.
The function datetime.combine() takes an optional argument tzinfo.

  • decimal – The decimal module has a new method Decimal.as_integer_ratio(). It returns (n,d)- a pair of integers representing a given Decimal instance as a fraction.
>>> Decimal('-3.14').as_integer_ratio()

(-157, 50)

  • k. distutils – Python 3.6 removes the default_format attribute from distutils.command.sdist.sdist. Also, now, the formats attribute defaults to [‘gztar’].
  • l. encodings – On Windows, we now have the ‘oem’ encoding for ‘CPOEMCP’. We also have the ‘ansi’ alias for ‘mbcs’ encoding.
  • m. enum – The enum module has two new enumeration base classes- Flag and IntFlags. These define constants that we can combine using bitwise operators.
>>> from enum import Enum, auto
>>> class Color(Enum):
    red=auto()
    blue=auto()
    green=auto()
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]
  •  faulthandler – This module installs a handler for Windows exceptions.
  •  fileinput – With Python 3.6, hook_encoded() supports the ‘errors’ argument.
  • http.client – Now, chunked encoding request bodies work with both HTTPConnection.request() and endheaders().
  • idlelib and IDLE – The idlelib package is refactored to give the IDLE a better look and better performance. This also makes the code easier to understand, test, and improve.
  •  importlib – Now, importlib raises the exception ModuleNotFoundError when it is unable to find a module. This is a subclass of ImportError.
  • inspect – Now, the function inspect.signature() reports the implicit .0 parameters that the compiler generates for comprehension and generator expression scopes.
  •  json – Now, json.load() and json.loads() support binary input.
  • logging – To check if a log file must be reopened, we have WatchedFileHandler.reopenIfNeeded().

Read: Python Collections Module

  • math – We have the new constant tau(τ) in both math and cmath modules.
  •  multiprocessing – We can now nest proxy objects returned by multiprocessing.Manager().
  • x. os – Now, scandir() supports bytes paths on Windows. The method close() lets us explicitly close a scandir() iterator.
  • pathlib – Now, pathlib supports path-like objects.
  •  pdb – Python 3.6 adds a new optional readrc argument to the class constructor. This controls whether .pdbrc files should be read. This is what’s new in Python 3.6, but this is not it.
  •  pickle – Pickle is the module that helps with serialization. We can now use pickle protocols older than protocol version 4 to pickle objects needing __new__ called with keyword arguments.
  •  pickletools – Now, pickletools.dis() outputs the implicit memo index for the MEMOIZE opcode.
  • ac. pydoc – With Python 3.6, pydoc has learned to respect the MANPAGER environment variable.
  • random – With the new random module, choices() returns a list of elements of a certain size. It picks these elements from a given population of optional weights.
  • re – The module re now has support for modifier spans in regular expressions. For instance, ‘(?i:p)ython’ will match ‘python’ and ‘Python’, but not ‘PYTHON’.
  • readline – The function set_auto_history() can enable/disable automatic addition of input to the history list.
  • rlcompleter – We no longer have private and special attribute names unless prefixed with an underscore. Sometimes, you can see a space or colon after some completed keywords.
  • shlex – To control what characters must be treated as punctuation, shlex now has much improved shell compatibility. This is through the punctuation_chars argument.
  • site – We can now specify file paths on top of directories to add paths to sys.path in a .pth file.
  • aj. sqlite3 – Now, sqlite3.Cursor.lastrowid supports the REPLACE statement.
  • ak. socket – getsockopt() now supports constants SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, and SO_PASSSEC.
    setsockopt() now supports the setsockopt(level, optname, None, optlen: int) form.
  • socketserver – The servers based on the socketserver module support the context manager protocol.
  • am. ssl – Now, ssl supports OpenSSL 1.1.0. Also, SSLContext now has better default configuration for options and ciphers.
  • statistics – The statistics module has the new harmonic_mean() function.
  • struct – Now, struct supports IEEE 754 half-precision floats. It does this via the ‘e’ format specifier.
  • subprocess – With Python 3.6, if the child process is still running, the subprocess.Popen destructor emits a ResourceWarning warning.
  • sys – The function getfilesystemencodeerrors() returns the name of the error mode used to convert between Unicode filenames and bytes filenames.
  • telnetlib – Now, Telnet is a context manager.
  • time – struct_time attributes tm_gmtoff and tm_zone now work on all platforms.
  • timeit – When there is substantial (4x) variance between best and worst times, timeit warns.
  • tkinter – New methods in the tkinter.Variable class include trace_add(), trace_remove() and trace_info().
  • traceback – Along with the interpreter’s built-in exception display, the traceback module abbreviate long sequences of repeated lines in tracebacks. For instance:
>>> def f(): f()
...
>>> f()

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

File “<stdin>”, line 1, in f

File “<stdin>”, line 1, in f

File “<stdin>”, line 1, in f

[Previous line repeated 995 more times]

RecursionError: maximum recursion depth exceeded

  • aw. tracemalloc – tracemalloc now supports tracing memory allocations in multiple different address spaces.
  • typing – This module now has an improved support for generic type aliases. Also, new classes include typing.ContextManager and typing.Collection.
  • unicodedata – This module now uses data from Unicode 9.0.0.
  • unittest.mock – New methods include Mock.assert_called() and Mock.assert_called_once().
  • urllib.request – If an HTTP request has a file or iterable body, other than a bytes object, but no Content-Length header, it does not throw an error. Now, AbstractHTTPHandler uses chunked transfer encoding.
  •  urllib.robotparser – The RobotFileParser now supports the Crawl-delay and Request-rate extensions.
  • venv – venv now accepts a new parameter-   –prompt. This is an alternative prefix for the virtual environment.
  • warnings – The warnings.warn_explicit() function now has an optional ‘source’ parameter.
  • winreg – What’s new? The 64-bit integer type REG_QWORD.
  • winsound – winsound now allows us to pass keyword arguments to Beep, MessageBeep, and PlaySound.
  • bg. xmlrpc.client – This module now supports unmarshalling additional data types that are used by the Apache XML-RPC implementation for numerics and None.
  •  zipfile – The class method ZipInfo.from_file() allows us to make a ZipInfo instance from a filesystem file.
  • zlib – We can now pass keyword arguments to functions compress() and decompress().

So, this is all on what’s new in Python 3.6 Tutorial. Hope you like our explanation.

7. Conclusion

In this article on what’s new in Python 3.6, we discussed what changes have been made to Python 3.5 to make it Python 3.6. Tell us how you like them the what’s new in Python 3.6 article.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

No Responses

  1. Neha says:

    Hi,
    I am new to Python and Data Science and looking for some blogs or websites where I can find some problem statements or Programs for Hands on purpose in Python and Machine Learning.
    Could you please suggest if possible.

Leave a Reply

Your email address will not be published. Required fields are marked *