Python

Julian Berman

https://github.com/Julian

tos9@Freenode

Generalities

  • Readable
  • Simple
  • Dynamic
  • Interpreted
  • Strongly typed

    • 2 + "2"
    • 
      Traceback (most recent call last):
        File "input", line 1, in module
      TypeError: unsupported operand type(s) for +: 'int' and 'str'
                        

Environment

  • Open source
  • Mature
  • Large community
  • Preinstalled

That funny language with semantic whitespace

Competency

Basics


>>> 12 + 2
14
          

>>> "hello" + ' ' + "world"
"hello world"
          

>>> cats = 12.3
>>> lives = 9j
>>> print cats * lives
110.7j
          

Data Types


favorite_things = ["dogs", "Filbert", "Jackie Chan"]
          

row = "Enrico", True, 1, "Narcoleptic", ["Wallet", "Key"]
          

vehicles = {"Thomas", "Lightning McQueen"}
          

board = {
    "A2" : ("White", "Pawn"),
    "B1" : ("White", "Rook"),
    "B8" : ("Black", "Rook"),
    "F5" : ("Black", "Knight"),
    "G7" : ("White", "King"),
    "H7" : ("Black", "King"),
}
          

Functions and Loops


def print_long_things(things, longer_than=3, finish_msg="Done!"):
    for thing in things:
        if len(thing) > longer_than:
            print thing
    print finish_msg
          

Functions and Loops


def print_long_things(things, longer_than=3, finish_msg="Done!"):
    for thing in things:
        if len(thing) > longer_than:
            print thing
    print finish_msg

>>> print_long_things(["the", "quick", "brown", "fox"])
quick
brown
Done!
          

Functions and Loops


def print_long_things(things, longer_than=3, finish_msg="Done!"):
    for thing in things:
        if len(thing) > longer_than:
            print thing
    print finish_msg

>>> print_long_things(things=["cat", "walrus"], finish_msg="OK!")
walrus
OK!
          

Comprehensions


numbers = range(10)
          
  • 
      [1, 2, 3]
                
  • 
      [number ** 2 for number in numbers]
                
  • 
      {1, 2, 3}
                
  • 
      {float(number) for number in numbers if number % 2 == 0}
                
  • 
      {1 : 2, 3 : 4}
                
  • 
      {number : number ** 2 for number in numbers if number % 2 == 0}
                

Generator Expressions


(number ** 2 for number in numbers if number % 2 == 0)
          

def make_numbers(numbers):
    for number in numbers:
        if number % 2:
            yield number
          

Synthesis

Synthesis

  • Everything is an object.
  • Most operations are overloadable.
  • Many batteries are included (though some are defective).
  • No object is special.

Objects


>>> movements = [1, -3, 5, 2, 3, -7, 4, 0, 2, -2]
>>> for movement in sorted(movements, key=abs):
...     print movement
          

0
1
2
2
-2
-3
3
4
5
-7
          

Python is like the NSA

Nothing is private.

How I Learned to Stop Typing and Love the Duck

"If it quacks like a duck, walks like a duck..."

How I Learned to Stop Typing and Love the Duck

"If it quacks like a duck, walks like a duck..."

Ducks

Types

Great for compilers

Not so great for humans

Ducks


class File {
  ...
}

class Parser {
    new(File inputFile) {
        List buffer = []
        while (String line = inputFile.readline() != EOF) {
            buffer.append(parse(line))
        }
    }
}
          

Ducks


class File extends Enumerable {
  ...
}

class Parser {
    new(Enumerable input) {
        List buffer = []
        while (String line = input.next() != EOI) {
            buffer.append(parse(line))
        }
    }
}
          

Ducks

  • I want a sequence
  • Do you have the right methods?
  • You're good to go.

Ducks

  • I want to call a function
  • What kind of object does it expect?

sorted


>>> sorted(["the", "cat", "in", "the", "hat"])
['cat', 'hat', 'in', 'the', 'the']
          
sorted(iterable, cmp=None, key=None, reverse=False)
      --> new sorted list

with open("shakespeare.txt") as input_file:
    print sorted(input_file)
          
Protocols

Let's Be Concrete

The Standard Library

itertools

The Standard Library

subprocess


import subprocess
processes = subprocess.check_output(["ps", "aux"])
          

The Rest

  • os
  • os.path
  • sys
  • glob

import os
import glob
import sys


for path in glob.iglob("css/*.css"):
    sys.stdout.write(os.path.abspath(path) + " ")
          

The Rest

  • argparse
  • json
  • sqlite3
  • Compression libraries
  • decimal, math, fractions
  • Tkinter
  • gettext
  • difflib
  • bisect
  • logging

Full Stack