Python 3
   Андрей Светлов

      @andrew_svetlov
andrew.svetlov@gmail.com
http://asvetlov.blogspot.com
Releases
2.6 — Oct 2008
3.0 — Dec 2008
3.1 — Jul 2009
2.7 — Jul 2010
3.2 — Feb 2011
3.3 — Aug 2012
Строки


         Только unicode

 Utf-8 — кодировка по умолчанию

Неявные преобразования str↔bytes
          запрещены.
Числа


      Unified int

 Long — отсутствует

Дерево числовых типов

Decimal — теперь на C
Форматирование строк



"{a:s} {b:.2f}".format(a='строка', b=3.14159)

"{c[0]}-{c[1]}".format(c=(1, 2))

"{0.x}, {0.y}".format(coord)
Function annotations


def f(a: int, b: float) -> str:
  return "{}:{}".format(a, b)

>>> f.__annotations__
{'a': builtins.int, 'b': builtins.float,
    'return': builtins.str}
Nonlocal

def f():
   a=0
   def g():
      nonlocal a
      a += 1
   g()
   return a
Keyword only
>>> def f(a, b=0, *, c, d='Smith'):
...   pass
>>> f(1, c='John', d='Doe')
>>> f(1, c='Mary')
>>> f(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() needs keyword-only argument c
Extended iterable unpacking
a, *rest = range(5)
a, *rest, b = range(5)
Comprehensions
{key(k): value(k) for k in range(5)}


{f(k) for k in range(5)}


{1, 2, 3, 4, 5}
ABC and new `super()`
class Base(metaclass=abc.ABCMeta):
  @abc.abstractmethod
  def f(self, a):
    """Comprehensive doc"""
    pass


class A(Base):
  def f(self, a):
Exception chain
def f():
      try:
         1/0
      except Exception as ex:
         raise RuntimeError("Oops") from ex
f()
Exception chain 2
Traceback (most recent call last):
 File "<string>", line 3, in f
   1/0
ZeroDivisionError: division by zero


 The above exception was the direct cause of
the following exception:


Traceback (most recent call last):
Абстрактные типы для коллекций
Hashable
Iterable
Sized
Container
Callable
Sequence
etc.
OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange':
 2}


# dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t:
 t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange',
 2), ('pear', 1)])
Counter
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red',
…          'green', 'blue', 'blue']:
...   cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
Yield from
>>> def g(x):
...   yield from range(x, 0, -1)
...   yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
Новые метаклассы
class OrderedClass(type):
  @classmethod
   def __prepare__(metacls, name, bases,
 **kwds):
    return collections.OrderedDict()
  def __new__(cls, name, bases, classdict):
     result = type.__new__(cls, name, bases,
 dict(classdict))
    result.members = tuple(classdict)
Незаметные вкусности
Новый GIL
Importlib
Stable ABI
PYC repository dirs
ABI version tagged .so files
Packaging
Вопросы?
      @andrew_svetlov
andrew.svetlov@gmail.com
http://asvetlov.blogspot.com

Py3k

  • 1.
    Python 3 Андрей Светлов @andrew_svetlov andrew.svetlov@gmail.com http://asvetlov.blogspot.com
  • 2.
    Releases 2.6 — Oct2008 3.0 — Dec 2008 3.1 — Jul 2009 2.7 — Jul 2010 3.2 — Feb 2011 3.3 — Aug 2012
  • 3.
    Строки Только unicode Utf-8 — кодировка по умолчанию Неявные преобразования str↔bytes запрещены.
  • 4.
    Числа Unified int Long — отсутствует Дерево числовых типов Decimal — теперь на C
  • 5.
    Форматирование строк "{a:s} {b:.2f}".format(a='строка',b=3.14159) "{c[0]}-{c[1]}".format(c=(1, 2)) "{0.x}, {0.y}".format(coord)
  • 6.
    Function annotations def f(a:int, b: float) -> str: return "{}:{}".format(a, b) >>> f.__annotations__ {'a': builtins.int, 'b': builtins.float, 'return': builtins.str}
  • 7.
    Nonlocal def f(): a=0 def g(): nonlocal a a += 1 g() return a
  • 8.
    Keyword only >>> deff(a, b=0, *, c, d='Smith'): ... pass >>> f(1, c='John', d='Doe') >>> f(1, c='Mary') >>> f(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() needs keyword-only argument c
  • 9.
    Extended iterable unpacking a,*rest = range(5) a, *rest, b = range(5)
  • 10.
    Comprehensions {key(k): value(k) fork in range(5)} {f(k) for k in range(5)} {1, 2, 3, 4, 5}
  • 11.
    ABC and new`super()` class Base(metaclass=abc.ABCMeta): @abc.abstractmethod def f(self, a): """Comprehensive doc""" pass class A(Base): def f(self, a):
  • 12.
    Exception chain def f(): try: 1/0 except Exception as ex: raise RuntimeError("Oops") from ex f()
  • 13.
    Exception chain 2 Traceback(most recent call last): File "<string>", line 3, in f 1/0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last):
  • 14.
    Абстрактные типы дляколлекций Hashable Iterable Sized Container Callable Sequence etc.
  • 15.
    OrderedDict >>> d ={'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # dictionary sorted by key >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
  • 16.
    Counter >>> cnt =Counter() >>> for word in ['red', 'blue', 'red', … 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1})
  • 17.
    Yield from >>> defg(x): ... yield from range(x, 0, -1) ... yield from range(x) ... >>> list(g(5)) [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
  • 18.
    Новые метаклассы class OrderedClass(type): @classmethod def __prepare__(metacls, name, bases, **kwds): return collections.OrderedDict() def __new__(cls, name, bases, classdict): result = type.__new__(cls, name, bases, dict(classdict)) result.members = tuple(classdict)
  • 19.
    Незаметные вкусности Новый GIL Importlib StableABI PYC repository dirs ABI version tagged .so files Packaging
  • 20.
    Вопросы? @andrew_svetlov andrew.svetlov@gmail.com http://asvetlov.blogspot.com