2.7v3.5

Comparisons

Strings

Division

2, truncates by default:

3/2 => 1

3.0//2 => 1.0

3, // for truncating

3.0/2 => 1

3//2 => 1

Iterators 3 vs Lists 2

Optimized native functions used iterators in 3 vs lists in 2

i.e range, map, filter, dict.[ft], zip

Print

In 2 can do print Hello

In 3, print is a regular ft so must include () print(Hello)

Raw Input in 2.7 s now input in 3

2.7 Specific Stuff

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Import python 3 functionality(good for migration and changes fundamental python props), needs to be near top of code because imported differently and changes things about language

3.5 New Features

Dictionary Comprehensions

{k: v for k, v in stuff}

Iterable Unwrapping

#Python 2
first, rest, last = seq[0], seq[1:-1], seq[-1]
#Python 3
first, *rest, last = seq

Objects

python 3 has different objects or something look it up

Formatting Print

name = 'World'
program = 'Python'
print(f'Hello {name}! This is {program}')

Typing Hinting

This doesn't make python a staticly typed language suddenly, but basically inline comments

def greeting(name: str) -> str:
    return 'Hello ' + name

Type Alias

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

Dataclass

Actually creates a __str and __init for you

from dataclasses import dataclass

@dataclass
class Armor:
    armor: float
    description: str
    level: int = 1

    def power(self) -> float:
        return self.armor * self.level

armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4
print(armor)

Actually Type Checking

Use pycharm or something with this (atom has a mypy plugin)

OR

pip install mypy

mypy [file]

Last updated