Show Menu
Cheatography

marcos-gral Cheat Sheet by

Python Classes

class Child(­Par­ent):
def __init­__(­self, args, *kwargs):
super(­)._­_in­it_­_(self, args) # ???
@stati­cmethod # ?????
@class­method # ?????
@property # for getter
@prope­rty.setter

Python

lambda [parameter_list]: expresion

def func(n):
    """ Documentation """

Python Indexes and Slices

len(a)
a[::-1] # reverse
b=a[:] # Shallow copy

Python Lists

lst.ap­pen­d(item)
lst.po­p(item)
lst.co­unt­(item)
lst.re­mov­e(item) # first item found
del lst[i]
lst.ex­ten­d(lst2)
lst.re­verse()
lst.in­dex­(item)
lst.sort()
sorted(ll) # sorts without modifying
lst.in­ser­t(p­osi­tion, item)
[x for x in lst if cond]

Dictionary Operations

len(d)
del d[key] # KeyError Exception
k in d
d.keys()
d.setd­efa­ult­(ke­y[,­def­ault]) # ???
d.clear() # ???
dict(a=1, b=2)
dict(z­ip(­['a', 'b'], [1, 2]))
dict(­­[('A', 1), ('Z', -1)])
dict(­­{'Z': -1, 'A': 1})

Compre­hen­sions

list
[ expression for iterab­­le­_­c­lause if option­­al­_­f­il­ter]
nested lists
[ expression for iterab­­le­_­c­la­­use_1 for iterab­­le­_­c­la­­use_2 if option­­al­_­f­il­ter]
dict
{ key_ex­­pr­e­s­sion: value_­­ex­p­r­ession for iterab­­le­_­c­lause if option­­al­_­f­il­ter}
set
{ value_­­ex­p­r­ession for iterab­­le­_­c­lause if option­­al­_­f­il­ter}

Python Scripting

sys.argv
parametes pass to the command
sys.ex­it(0)
0 is success
sys.path
list of paths to packages
sys.ve­rsi­on_info
os.environ
Dictionary of enviro­nment Vars
os.curdir

Python requests

r = requests.get(url , params={'foo': 'bar'} )
r = requests.post(url , params={'foo': 'bar'} )

r.status_code # 200
r.text
r.json
r.headers
r.encoding # utf-8 / ISO-xxx

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
 
r = requests.post(url, data=json.dumps(payload), headers=headers)

r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")

Python Datetime

dt.today()
dt.now­(ti­mez­one­info)
dt.com­bin­e(date, time)
dt.utc­now()
dt.str­pti­me(­date, format)
dt.fro­mti­mes­tam­p(t­ime­stamp)
dt.tim­est­amp() # ????
dt.utc­fro­mti­mes­tam­p(t­ime­stamp)
from datetime import datetime as dt

Python Time Methods

time.r­epl­ace()
time.u­tco­ffset()
time.i­sof­ormat()
time.dst()
time.t­zname()

Python Date Formatting

Python Iteration

for i in range(start,stop,step):
    stuff

for value in [sequence]:
    stuff

for position, value in enumerate(sequence):
    stuff

for a,b in zip(first, second):
   stuff

for ###
else
    stuff to do at end of loop (usually exception when breaking in loop)

while condition:
    stuff
else
    stuff to do when condition is false

break # breaks the loop
continue # continue at the start of the loop body
module itertools provides lots of intere­­sting tools for iteration

varios

"­Hello, %s." % name
"­Hello, %s. You are %s." % (name, age)

"­Hello, {}. You are {}.".fo­rma­t(name, age)
"­Hello, {1}. You are {0}.".f­orm­at(age, name)

person = {'name': 'Eric', 'age': 74}
"­Hello, {name}. You are {age}.".fo­rma­t(n­ame­=pe­rso­n['­name'], age=pe­rso­n['­age'])
"­Hello, {name}. You are {age}.".fo­rma­t(**­pe­rson)

>>> name = "­Eri­c"
>>> age = 74
>>> f"Hello, {name}. You are {age}."­

F"Hello, {name}. You are {age}."­

f"{n­ame.lo­wer()} is funny."­

f"{m­y:f­unc­(name)} is funny."­

https:­//r­eal­pyt­hon.co­m/p­yth­on-­f-s­trings/
======­===­===­===­===­===­===­===­===­===­===­===­======

Operations on Sets ????

|
union
&
inters­ection
-^
differ­enc­e/s­ymetric diff
< <= > >=
inclusion relations
s.upda­te(s2)
s.add(key)
s.copy()
s.disc­ard­(key)
s.pop()
s.clear()
 

Python Math

5 // 2 = 2
5 % 2 = 1

Python Generators

yield x
next(func)
genera­tor.se­nd(x)
for in in genera­­to­r­_­fu­­nct­­io­n­(­**­­som­­e_­p­a­rams)
yield from list_c­­om­p­r­eh­­ension # ????

in-built functions

min(va­lues), max(va­lues)
range(­start, stop[, step])
filter­(fu­nction, array) # ???
map(func, array) # ???
id(object)
round(n, [decimal places]

Python Common Exceptions

IndexError
KeyError
StopIt­eration
Timeou­tError
Attrib­ute­Error
Assert­ion­Error

Python Random

random.se­ed(1)
random.ra­ndr­ang­e(stop)
random.ra­ndr­ang­e(s­tart, stop[,­step])
random.ra­ndi­nt(a, b)
random.ch­oic­e(seq)
random.ch­oic­es(­pop­ula­tion, k=1) # IndexError
random.sh­uff­le(x)
random.sa­mpl­e(p­opu­lation, k)

Python File

f = open(path)
f.read() # Read f
f.read­line()
f.read­lines()
f.write(s)
f.close()
with f = open(path, 'r'):

Python Regular expres­sions Module

re.com­pil­e(p­attern, flags=0)
regex.s­ea­rch­(st­rin­g[,­pos­][,­end­pos])
regex.m­at­ch(­string)
regex.f­ul­lMa­tch­(st­ring)
match.g­ro­up(­[gr­oup1, ...])
match.g­ro­ups()

Python String Methos

s.lstr­inp()
s.part­ition()
s.decode() # ???
s.rjus­t(w­irth[, fillchar])
s.rfin­d(item)
s.spli­t(sep)
s.spli­tli­nes()
s.isal­pha()
s.isdi­git()
s.star­tsw­ith­(sub)
s.strip()
s.issp­ace()
s.enco­de(­'ut­f-8') # ???
b"st­rin­g" # bytes object

String Formating

"­Hello, {0} {1}".fo­rma­t("a­be", "­jon­es")
Hello, abe jones

"­Hello, {fn} {ln}".f­orm­at(­fn=­"­abe­", ln="­jon­es")
Hello, abe jones

"You owe me ${0:,.2­f}­".fo­rma­t(2­534­22.3)
You owe me $253,4­22.30

now = dateti­me.n­ow()
'{:%Y-­%m-%d %H:%M:­%S}­'.f­orm­at(now)
2012-­05-16 15:04:33

Exceptions

try:
except ExceptionName as e:
except (ExceptionName, OtherException) as e:
else:
    # do something when no exception
finally:
    # do something anyway, exception or not

Code Snippets

Loop Over Sequence
for index, value in enumer­ate­(seq):
 ­ ­pri­nt(­"{} : {}".f­or­mat­(index, value))

Loop Over Dictio­nary
for key in sorted­(dict):
 ­ ­pri­nt(­dic­t[key])

Read a File
with open("f­ile­nam­e", "­r") as f:
 ­ for line in f:
 ­ ­ ­ line = line.r­str­ip(­"­\n") # Strip newline
 ­ ­ ­ ­pri­nt(­line)

Python Decorator

def wrap(func):
    def wrapper(args, *kwargs):
        # do something about func
        func(args, *kwargs)
        # do something about func
    return wrapper

# Apply decorator
def to_decorate(...):
# body	
to_decorate = wrap(to_decorate)	

# More idiomatic
@wrap
def to_decorate(...):
#body


from functools import wraps
@wraps(func)
def wrapper(...) # to keep the name and doc from the wrapped function

# Decorator with args: make a decorator factory
def decorator_factory(factory_args):
    def decorator(func):
        def wrapper(args, *kwargs):
            # do something about func
            func(args, *kwargs)
            # do something about func
        return wrapper
    return decorator


@decorator_factory(1,2...)
def to_decorate(...):

Iterator

class zrange_iter:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        # Iterators are iterables too.
        # Adding this functions to make them so.
        return self

    def next(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()

Generator

def firstn(n):
    num = 0
    while num < n:
        yield num
        num += 1

sum_of_first_n = sum(firstn(1000000))

# yield from my_gen(x)

g = my_gen(x)
try:
    next(g)
except StopIteration:
    pass

# Unpacking Generators

>>> g1 = (x for x in range(3))
>>> g2 = (x**2 for x in range(2))
>>> [1, g1, 2, g2]
[1, 0, 1, 2, 2, 0, 1]

>>> g = (x for x in range(3))
>>> a, b, c = g
>>> print(a, b, c)
0 1 2
>>> g = (x for x in range(6))
>>> a, b, *c, d = g
>>> print(a, b, d)
0 1 5
>>> print(c)
[2, 3, 4]
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          grep Cheat Sheet
          grep (english) Cheat Sheet
          KnowledgeBase Cheat Sheet