What's new in Python 3.7

Misha Behersky

https://github.com/bmwant

 

 

 

Kyiv.py #23

3.7.0 schedule

 

 

Installation

Download


wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0b1.tgz
tar -xvf Python-3.7.0b1.tgz
[sudo] apt-get install build-essential zlib1g-dev libreadline-dev libssl-dev openssl libffi-dev
cd Python-3.7.0b1/
./configure
make
[sudo] make install
      
voilĂ 

$ pip3.7 --version
pip 9.0.1 from /usr/local/lib/python3.7/site-packages (python 3.7)

$ python3.7 --version
Python 3.7.0b1

$ python3.7 -c "import sys; print(f'{sys.version}')"
3.7.0b1 (default, Feb 24 2018, 08:35:50)
[GCC 5.4.0 20160609]
      
PEP 562: Customization of access to module attributes

# mylib.py
from warnings import warn

deprecated_names = ['old_function']


def old_function():
    return 5.1


def __getattr__(name):
    if name in deprecated_names:
        warn(f'{name} is deprecated', DeprecationWarning)
        return globals()[name]
    raise AttributeError(f'module {__name__} has no attribute {name}')

# main.py
from mylib import old_function
      
PEP 553: Built-in breakpoint()

def function():
  breakpoint()  # by default same as import pdb; pdb.set_trace()
  return 553

import sys; sys.breakpointhook = lambda: print('Do not touch anything')

export PYTHONBREAKPOINT=0  # disable completely
      
PEP 563: Postponed evaluation of annotations

from __future__ import annotations

class C:
    @classmethod
    def from_string(cls, source: str) -> C:
        ...

    def validate_b(self, obj: B) -> bool:
        ...

class B:
    ...
      
PEP 564: Add new time functions with nanosecond resolution
  • time.clock_gettime_ns()
  • time.clock_settime_ns()
  • time.monotonic_ns()
  • time.perf_counter_ns()
  • time.process_time_ns()
  • time.time_ns()
PEP 557: Data Classes

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # Point(x=1.5, y=2.5, z=0.0)
      

import sys
from dataclasses import dataclass

@dataclass(frozen=True)
class ImmutableSimpleDataObject(object):
'''
In this case,
__init__, __repr__, __lt__, __eq__, __gt__ will all be generated automatically.
'''

field_a: int
field_b: str

example = {ImmutableSimpleDataObject(1, 'b'), ImmutableSimpleDataObject(2, 'c')}
print(example)
      
Data Classes. Post-Init processing. Default factory

import sys
from dataclasses import dataclass, field


def get_argv():
    return sys.argv[1]


@dataclass
class SimpleDataObject(object):
  field_a: str
  field_b: str = field(default_factory=get_argv)

  def __post_init__(self):
      self.field_b = self.field_b.upper()

example = SimpleDataObject(field_a = 'a')
print(example)  # Now SimpleDataObject(field_a='a', field_b='TEST')
      
PEP 567: Context Variables

import contextvars

var = contextvars.ContextVar('var')
var.set('spam')

def main():
    var.set('ham')

ctx = contextvars.copy_context()

# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)

print(ctx.get(var))  # ham
print(var.get())  # spam
      
Context Variables & asyncio

import asyncio
import contextvars

client_addr_var = contextvars.ContextVar('client_addr')

def render_goodbye():
    client_addr = client_addr_var.get()
    return f'Good bye, client @ {client_addr}\n'.encode()

async def handle_request(reader, writer):
    addr = writer.transport.get_extra_info('socket').getpeername()
    client_addr_var.set(addr)

    while True:
        line = await reader.readline()
        print(line)
        if not line.strip():
            break
        writer.write(line)

    writer.write(render_goodbye())
    writer.close()

async def main():
    srv = await asyncio.start_server(
        handle_request, '127.0.0.1', 8081)

    async with srv:
        await srv.serve_forever()

asyncio.run(main())
      
Pass context

        ctx = contexvars.Context()
        ctx = convexvars.copy_context()
        Loop.call_soon(), Loop.call_later(), and Loop.call_at()
      
PEP 552: Hash-based pycs
Other
  • PEP 538: Legacy C Locale Coercion
  • PEP 539: A New C-API for Thread-Local Storage in CPython
  • PEP 565: Show DeprecationWarning in __main__
  • PEP 540: Add a new UTF-8 mode
  • New Development Mode: -X dev
See more info here
And much more CPython speed improvements!
  • Calling methods faster
  • str.find() is faster for some characters
  • os.fwalk is 2x faster
  • Regular expressions are faster for case-insensitive matching
Release on github
Do not forget to check out

New aiohttp 3.0 release!

Read the docs
Resources
  1. A brief tour of Python 3.7 data classes
  2. 5 speed improvements in Python 3.7
  3. Python GitHub repo

Stay in touch | Q&A

@bmwant

bmwlog.pp.ua