Baptiste Mispelon
Online: bmispelon
Web developer
Django core dev since June 2013
Python has 69 builtin functions.
(80 in Python 2)
abs | dict | help | min | setattr |
all | dir | hex | next | slice |
any | divmod | id | object | sorted |
ascii | enumerate | input | oct | staticmethod |
bin | eval | int | open | str |
bool | exec | isinstance | ord | sum |
bytearray | filter | issubclass | pow | super |
bytes | float | iter | tuple | |
callable | format | len | property | type |
chr | frozenset | list | range | unichr |
classmethod | getattr | locals | repr | vars |
compile | globals | map | reversed | zip |
complex | hasattr | max | round | __import__ |
delattr | hash | memoryview | set |
abs | dict | help | min | setattr |
all | dir | hex | next | slice |
any | divmod | id | object | sorted |
ascii | enumerate | input | oct | staticmethod |
bin | eval | int | open | str |
bool | exec | isinstance | ord | sum |
bytearray | filter | issubclass | pow | super |
bytes | float | iter | tuple | |
callable | format | len | property | type |
chr | frozenset | list | range | unichr |
classmethod | getattr | locals | repr | vars |
compile | globals | map | reversed | zip |
complex | hasattr | max | round | __import__ |
delattr | hash | memoryview | set |
Quick and dirty introspection.
List of all the attributes/methods of an object (as strings).
What are all the public attributes of this object?
obj = 'hello world' [attr for attr in dir(obj) if not attr.startswith('_')]
What are all the public attributes of this object?
obj = 'hello world' [attr for attr in dir(obj) if not attr.startswith('_')] # ['capitalize', 'casefold', # 'center', 'count', ...]
Given two numbers, return a pair of quotient, remainder.
a, b = 42, 5 q, r = a // b, a % b q, r # ?
a, b = 42, 5 q, r = a // b, a % b q, r # 8, 2
a, b = 42, 5 q, r = divmod(a, b) q, r # 8, 2
Create slice objects.
s = 'abcdefghi' s[ :8] # ? s[1:8] # ? s[1:8:2] # ?
s = 'abcdefghi' s[ :8] # 'abcdefgh' s[1:8] # ? s[1:8:2] # ?
s = 'abcdefghi' s[ :8] # 'abcdefgh' s[1:8] # 'bcdefgh' s[1:8:2] # ?
s = 'abcdefghi' s[ :8] # 'abcdefgh' s[1:8] # 'bcdefgh' s[1:8:2] # 'bdfh'
s = 'abcdefghi' s[ :8] == s[slice(8)] s[1:8] == s[slice(1, 8)] s[1:8:2] == s[slice(1, 8, 2)]
Unordered collection of distinct objects.
>>> set('abcabcabc')
>>> set('abcabcabc') {'c', 'b', 'a'}
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1})
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1}) 3
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1}) 3 >>> sum({1, 2, 3, 2, 1})
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1}) 3 >>> sum({1, 2, 3, 2, 1}) 6
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1}) 3 >>> sum({1, 2, 3, 2, 1}) 6 >>> 3 in {1, 2, 3}
>>> set('abcabcabc') {'c', 'b', 'a'} >>> len({1, 2, 3, 2, 1}) 3 >>> sum({1, 2, 3, 2, 1}) 6 >>> 3 in {1, 2, 3} True
Since python 2.7:
set([1, 2, 3]) # Is the same as doing {1, 2, 3}
Since python 2.7 (too):
set(w.lower() for w in wordlist) # Is the same as doing {w.lower() for w in wordlist}
{1, 2} & {2, 3} {1, 2} | {2, 3} {1, 2} - {2, 3} {1, 2} ^ {2, 3} {1, 2} < {2, 3} {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} {1, 2} - {2, 3} {1, 2} ^ {2, 3} {1, 2} < {2, 3} {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} # {1, 2, 3} {1, 2} - {2, 3} {1, 2} ^ {2, 3} {1, 2} < {2, 3} {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} # {1, 2, 3} {1, 2} - {2, 3} # {1} {1, 2} ^ {2, 3} {1, 2} < {2, 3} {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} # {1, 2, 3} {1, 2} - {2, 3} # {1} {1, 2} ^ {2, 3} # {1, 3} {1, 2} < {2, 3} {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} # {1, 2, 3} {1, 2} - {2, 3} # {1} {1, 2} ^ {2, 3} # {1, 3} {1, 2} < {2, 3} # False {1, 2} < {3, 2, 1}
{1, 2} & {2, 3} # {2} {1, 2} | {2, 3} # {1, 2, 3} {1, 2} - {2, 3} # {1} {1, 2} ^ {2, 3} # {1, 3} {1, 2} < {2, 3} # False {1, 2} < {3, 2, 1} # True
Like a set, but immutable.
Making it immutable makes it hashable.
This means we can use it as the key of a dictionnary.
Or put it in another set/frozenset.
Making it immutable makes it hashable.
This means we can use it as the key of a dictionnary.
Or put it in another set/frozenset.
(Yo Dawg, I heard you like sets...)
Make an iterator out of an iterable.
>>> L = list('abc')
>>> L = list('abc') >>> ''.join(c.upper() for c in L)
>>> L = list('abc') >>> ''.join(c.upper() for c in L) 'ABC'
>>> L = list('abc') >>> ''.join(c.upper() for c in L) 'ABC' >>> ''.join(c.upper() for c in L)
>>> L = list('abc') >>> ''.join(c.upper() for c in L) 'ABC' >>> ''.join(c.upper() for c in L) 'ABC'
>>> I = iter('abc')
>>> I = iter('abc') >>> ''.join(c.upper() for c in I)
>>> I = iter('abc') >>> ''.join(c.upper() for c in I) 'ABC'
>>> I = iter('abc') >>> ''.join(c.upper() for c in I) 'ABC' >>> ''.join(c.upper() for c in I)
>>> I = iter('abc') >>> ''.join(c.upper() for c in I) 'ABC' >>> ''.join(c.upper() for c in I) ''
If you pass a second argument, iter behaves quite differently.
iter(callable, sentinel)
Call the first argument yielding the return value and stopping when the sentinel value is reached (or when the call raises StopIteration).
fp = open('mydata.txt') S = 'STOP\n' for line in iter(fp.readline, S): print(line)
fp = open('mydata.txt') S = 'STOP\n' for line in iter(fp.readline, S): print(line) # Print all lines and stop when # reading the one containing "STOP"
from random import choice def roll(): return choice(range(1, 7)) list(iter(roll, 6)) # [] list(iter(roll, 6)) # [4, 4, 1]
Advance an iterator and return the value.
Raise StopIteration if empty.
i = iter('abc') next(i) # ? next(i) # ? next(i) # ? next(i) # ?
i = iter('abc') next(i) # 'a' next(i) # ? next(i) # ? next(i) # ?
i = iter('abc') next(i) # 'a' next(i) # 'b' next(i) # ? next(i) # ?
i = iter('abc') next(i) # 'a' next(i) # 'b' next(i) # 'c' next(i) # ?
i = iter('abc') next(i) # 'a' next(i) # 'b' next(i) # 'c' next(i) # StopIteration
next takes a second argument.
Similar to dict.get, it's a value to return if the iterator is empty (instead of raising StopIteration).
i = iter('abc') next(i, 'x') # 'a' next(i, 'x') # 'b' next(i, 'x') # 'c' next(i, 'x') # ?
i = iter('abc') next(i, 'x') # 'a' next(i, 'x') # 'b' next(i, 'x') # 'c' next(i, 'x') # 'x'
I hope you've studied your maths lesson for this one...
Did you know that python has first class support for complex numbers?
a = complex(real=4, imag=1) b = complex(real=1, imag=2) a + b # ?
Did you know that python has first class support for complex numbers?
a = complex(real=4, imag=1) b = complex(real=1, imag=2) a + b # complex(5, 3)
Did you know that python has first class support for complex numbers?
a = complex(real=4, imag=1) b = complex(real=1, imag=2) a + b # complex(5, 3) a + b + 1 # ?
Did you know that python has first class support for complex numbers?
a = complex(real=4, imag=1) b = complex(real=1, imag=2) a + b # complex(5, 3) a + b + 1 # complex(6, 3)
It also has imaginary number litterals:
1 + 2j # complex(1, 2)
It also has imaginary number litterals:
1 + 2j # complex(1, 2) 3j # complex(0, 3)
It also has imaginary number litterals:
1 + 2j # complex(1, 2) 3j # complex(0, 3) 1j ** 2 # ?
It also has imaginary number litterals:
1 + 2j # complex(1, 2) 3j # complex(0, 3) 1j ** 2 # -1
>>> from math import e, pi
>>> from math import e, pi >>> e ** (1j * pi)
>>> from math import e, pi >>> e ** (1j * pi) -1
>>> from math import e, pi >>> e ** (1j * pi) (-1+1.2246467991473532e-16j) # Close enough :)
Looks for a FOO.py file on your python path and executes it.
$ echo "print('Hello')" > FOO.py $ python -m FOO Hello
python -m this
python -m __hello__
python -m antigravity
Some standard modules are written in a way that they can be used as standalone programs (not just imported).
Uses the "trick":
if __name__ == '__main__': # Put code here
python -m http.server
Browse and dowload files from the current directory (on port 8000 by default).
python -m http.server python2 -m SimpleHTTPServer
Browse and dowload files from the current directory (on port 8000 by default).
class Foo(object): def foo(self): return 42 def bar(self): return 43
>>> f = Foo()
>>> f = Foo() >>> f.foo()
>>> f = Foo() >>> f.foo() 42
>>> f = Foo() >>> f.foo() 42 >>> f.bar()
>>> f = Foo() >>> f.foo() 42 >>> f.bar() AttributeError: 'Foo' object has no attribute 'bar'
>>> f = Foo() >>> f.foo() 42 >>> f.bar() AttributeError: 'Foo' object has no attribute 'bar' # WAT!?
class Foo(object): def foo(self): return 42 def bar(self): return 43
class Foo(object): ....def foo(self): ........return 42 --->def bar(self): --->--->return 43
class Foo(object): def foo(self): return 42 def bar(self): return 43
python -m tabnanny your_file.py
python -m calendar
python -m calendar python -m calendar 2015
python -m calendar python -m calendar 2015 10
python -m base64 some_file
python -m webbrowser \ "http://google.pl"
python -m pydoc str.find
python -m pydoc \
yourmodule.yourfunction
python -m pyclbr your_file.py python -m pyclbr modulename
python -m pyclbr your_file.py python -m pyclbr modulename
Safe to run on arbitrary files.
An arbitrary selection of useful modules,
for use in python code.
with open('file.csv') as f: for line in f: row = line.split(',') print(row)
import csv with open('file.csv') as f: for row in csv.reader(f): print(row)
def is_leap(year): return (year % 4) == 0
def is_leap(year): return (year % 4) == 0 # Hmm... wait
def is_leap(year): return (year % 4) == 0 \ and (year % 100) != 0 # Aah, that's better
def is_leap(year): return (year % 4) == 0 \ and (year % 100) != 0 # ... or is it?
import calendar calendar.isleap(2013)
password = input("Password: ")
from getpass import getpass password = getpass()
s = 'abcdefghijklmnoprstuvwxyz' s = '0123456789'
import string string.ascii_lowercase string.ascii_uppercase string.digits string.punctuation string.whitespace
from random import choice as ch S = 'abcdefghjklmnopqrstuvwxyz' name = ''.join( ch(S) for _ in range(8)) path = '/tmp/%s' % name temp = open(path, 'w')
import tempfile temp = tempfile.TemporaryFile()
import sys for fname in sys.argv[1:]: f = open(fname) for line in f: process(line)
import fileinput lines = fileinput.fileinput() for line in lines: process(line)
import fileinput lines = fileinput.fileinput() for line in lines: process(line) # It even supports - for STDIN
N = len(text) // 80 for i in range(N): print(text[i*80:(i+1)*80])
import textwrap lines = textwrap.wrap(text, width=80) print('\n'.join(lines))
import textwrap print(textwrap.fill(text, width=80))
kw = ['class', 'for', 'if', ...]
import keyword keyword.kwlist
import keyword keyword.kwlist keyword.iskeyword('class')
print('Kąt')
print('Kąt') # <insert joke about angular.js>
print('Kąt') print('K\x0105t')
print('Kąt') print('K\x0105t') print('K\u0105t')
print('Kąt') print('K\x0105t') print('K\u0105t') print('K\U00000105t')
print('Kąt') print('K\x0105t') print('K\u0105t') print('K\U00000105t') print('K\N{LATIN SMALL LETTER A\ WITH OGONEK}t')
>>> from unicodedata import ( name, lookup) >>> name('ą') 'LATIN SMALL LETTER A WITH OGONEK' >>> lookup('LATIN SMALL LETTER A ' ... 'WITH OGONEK') 'ą'
import os for fname in os.listdir('.'): if fname.endswith('.txt'): print(fname)
import glob for fname in glob.glob('*.txt'): print(fname)
colorsys, difflib, fractions, fnmatch, robotparser, wave, shlex, contextlib, inspect, ...
Python is awesome.
Go look in your /usr/lib/python/, see what you can find.