2.

Python

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() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  
abs(x)

(magnitude)

all(iterable)

iterable ( iterable ) True :

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
any(iterable)

iterable True iterable False :

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
ascii(object)

repr() repr() ASCII \x \u \U Python 2 repr()

bin(x)

"0b" 2 Python

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

"0b"

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

format()

class bool([x])

True False x x False True bool int ( int, float, complex ) False True ( )

class bytearray([source[, encoding[, errors]]])

bytearray 0 <= x < 256 bytes see bytes bytearray )

source :

0

bytes, bytearray, memoryview bytearray

class bytes([source[, encoding[, errors]]])

0 <= x < 256 "bytes" bytes bytearray

bytearray()

bytes, bytearray, memoryview, , bytes bytearray

callable(object)

object True False object () __call__()

3.2 : Python 3.0 Python 3.2

chr(i)

Unicode i chr(97) 'a' chr(8364) '' ord()

0 1,114,111 (16 0x10FFFF) i ValueError

@classmethod

:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

@classmethod (decorator)

( C.f()) ( C().f())

C++ Java staticmethod()

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

source AST exec() eval() source AST AST AST ast

filename ; ('<string>' )

mode ; source 'exec' 'eval' 'single' ( None )

The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile(). If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it the future statements in effect around the call to compile are ignored.

future OR __future__ _Feature compiler_flag

optimize ; -1 -O 0 ( __debug__ ) 1 (assert __debug__ ) 2 (docstring )

SyntaxError ValueError

Python AST ast.parse()

'single' 'eval' code

It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Pythons AST compiler.

3.2 : Windows Mac 'exec' optimize

3.5 : source TypeError

class complex([real[, imag]])

real + imag*1j () imag int float 0j

+ - complex('1+2j') complex('1 + 2j') ValueError

int, float, complex

3.6 :

delattr(object, name)

setattr() delattr(x, 'foobar') del x.foobar

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

dict dict dict

list, set, tuple collections

dir([object])

__dir__() __getattr__() __getattribute__() dir()

__dir__() __dict__ __getattr__()

dir() :

:

>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module 
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
divmod(a, b)

2 () (a // b, a % b) (q, a % b) q math.floor(a / b) 1 q * b + a % b a a % b b 0 <= abs(a % b) < abs(b)

enumerate(iterable, start=0)

enumerate iterable iterator enumerate() __next__() ( 0 start ) iterable

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
eval(expression, globals=None, locals=None)

globalslocals globals locals

expression Python () globals locals globals '__builtins__' expression globals expression builtins locals globals eval() :

>>> x = 1
>>> eval('x+1')
2

(compile() ) mode 'exec' eval() None

: exec() globals() locals() eval() exec()

ast.literal_eval()

exec(object[, globals[, locals]])

Python object Python () [1] ( "file-input" ) return yield exec() None

globals globals locals locals exec globals locals

globals __builtins__ builtins exec() globals __builtins__

locals locals() : locals exec() locals locals

filter(function, iterable)

iterable function iterable function None iterable

filter(function, iterable) None (item for item in iterable if function(item)) None (item for item in iterable if item)

function iterable itertools.filterfalse()

class float([x])

x

10 '+' '-' '+' NaN (not-a-number) :

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

floatnumber Python "inf" "Inf" "INFINITY" "iNfINity"

(Python ) Python OverflowError

Python x float(x) x.__float__()

0.0

:

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

int, float, complex

3.6 :

format(value[, format_spec])

value format_spec "" format_spec value :

format_spec str(value)

format(value, format_spec) type(value).__format__(value, format_spec) value __format__() object format_spec format_spec TypeError

3.4 : format_spec object().__format__(format_spec) TypeError

class frozenset([iterable])

frozenset iterable frozenset frozenset set set, frozenset

set, list, tuple, dict collections

getattr(object, name[, default])

object name getattr(x, 'foobar') x.foobar default AttributeError

globals()

()

hasattr(object, name)

True False ( getattr(object, name) AttributeError )

hash(object)
() (1 1.0 )
help([object])

()

site

3.4 : pydoc inspect

hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with "0x". If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

16 16 "0x" "0x" :

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

format()

1616 int()

id(object)

"" 2 id()

CPython : This is the address of the object in memory.

input([prompt])

prompt 1 () EOF EOFError :

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

readline input()

class int(x=0)
class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). If x defines x.__trunc__() but not x.__int__(), then return if x.__trunc__(). For floating point numbers, this truncates towards zero.

x base x bytes bytearray base + - () n 0 n-1 10-35 a z ( A Z) base 10 0 236 2, 8, 16 0b/0B, 0o/0O, 0x/0X 0 2, 8, 10, 16 int('010', 0) int('010') int('010', 8)

int, float, complex

3.6 :

isinstance(object, classinfo)

object classinfo ( ) object classinfo () object classinfo TypeError

issubclass(class, classinfo)

class classinfo ( virtual) classinfo classinfo TypeError

iter(object[, sentinel])

(iterator) object (__iter__() ) ( 0 __getitem__() ) TypeError sentinel object __next__() object sentinel StopIteration

iter() 2 readline() :

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
len(s)

() (range ) ()

class list([iterable])

list (list) list, tuple, range

locals()

locals()

;

map(function, iterable, ...)

function iterable iterable function itertools.starmap()

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

iterable 2

1 iterable iterable 2

2 key 1 (list.sort() ) default default ValueError

sorted(iterable, key=keyfunc, reverse=True)[0] heapq.nlargest(1, iterable, key=keyfunc)

3.4 : default

memoryview(obj)

""

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

iterable 2

1 iterable iterable 2

2 key 1 (list.sort() ) default default ValueError

sorted(iterable, key=keyfunc)[0] heapq.nsmallest(1, iterable, key=keyfunc)

3.4 : default

next(iterator[, default])

iterator __next__() default StopIteration

class object

object Python

oct(x)

Convert an integer number to an octal string prefixed with "0o". The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

If you want to convert an integer number to octal string either with prefix "0o" or not, you can use either of the following ways.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

format()

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file OSError

file :term:path-like object () ( closefd False I/O )

mode 'r' () 'w' 'x' 'a' ( Unix )encoding :locale.getpreferredencoding(False) (rawencoding )

'r' ()
'w'
'x'
'a'
'b'
't' ()
'+' ()
'U' ()

'r' ('rt' ) 'w+b' 0 'r+b'

Python I/O (mode 'b' ) bytes ( mode 't' ) str encoding

Python ; Python

buffering () 0 () 1 1 buffering :

encoding text encoding (locale.getpreferredencoding() ) Python codecs

errors ( ) codecs.register_error() :

  • 'strict' ValueError None
  • 'ignore'
  • 'replace' ('?' )
  • 'surrogateescape' Unicode Private Use Area () U+DC80 U+DCFF surrogateescape
  • 'xmlcharrefreplace' &#nnn; XML
  • 'backslashreplace' Python
  • 'namereplace' () \N{...}

newline universal newlines ()None, '', '\n', '\r', '\r\n' :

  • newline None '\n', '\r', '\r\n' '\n' ''
  • newline None '\n' os.linesep newline '' '\n' newline '\n'

closefd False closefd True ()

opener opener (file, flags) opener (os.open opener None )

os.open() dir_fd :

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

open() file object open() ('w', 'r', 'wt', 'rt', ) io.TextIOBase ( io.TextIOWrapper) io.BufferedIOBase io.BufferedReader io.BufferedWriter io.BufferedRandom raw io.RawIOBase io.FileIO

fileinput (open() ) io os os.path tempfile shutil

3.3 :
3.4 :

3.4 4.0 : 'U'

3.5 :
3.6 :
ord(c)

1 Unicode Unicode ord('a') 97 ord('') () 8364 chr()

pow(x, y[, z])

x y ; z x y z (pow(x, y) % z ) pow(x, y) x**y

int () ; 10**2 100 10**-2 0.01 z x y y

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

objects sep file end sep end file flush

str() sep end sep end None objects print() end

file write(string) None sys.stdout print() file.write(...)

file flush

3.3 : flush

class property(fget=None, fset=None, fdel=None, doc=None)

property

fget fset fdel doc docstring

x :

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

c C c.x getter c.x = value setter del c.x deleter

doc property property fget () property() (decorator) property :

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

@property voltage() "getter" voltage "Get the current voltage."

property getter, setter, deleter property :

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

property ( x)

property fget, fset, fdel

3.5 :

range(stop)
range(start, stop[, step])

range range list, tuple, range

repr(object)

eval() () __repr__()

reversed(seq)

(reverse iterator) seq __reversed__() (__len__() 0 __getitem__() )

round(number[, ndigits])

number ndigists ndigits None

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.

For a general Python object number, round(number, ndigits) delegates to number.__round__(ndigits).

round() : round(2.675, 2) 2.68 2.67 :

class set([iterable])

iterable set set set set set, frozenset

collections frozenset list tuple dict

setattr(object, name, value)

getattr() setattr(x, 'foobar', 123) x.foobar = 123

class slice(stop)
class slice(start, stop[, step])

range(start, stop, step) (slice) start step None startstop step () Numerical Python a[start:stop:step] a[start:stop, i] itertools.islice()

sorted(iterable, *, key=None, reverse=False)

iterable

2

key 1 : key=str.lower None ()

reverse True

cmp key functools.cmp_to_key()

sort()

HOW TO

@staticmethod

:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod (decorator)

( C.f() ) ( C().f())

Python Java C++ classmethod()

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

class C:
    builtin_open = staticmethod(open)

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

object str str()

str str

sum(iterable[, start])

start iterable start 0 iterable start

sum() ''.join(sequence) math.fsum() itertools.chain()

super([type[, object-or-type]])

type type getattr()

type __mro__ getattr() super()

2 2 isinstance(obj, type) 2 issubclass(type2, type) ()

super 2 super super

2 Python "diamond diagram" ()

:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

super() super().__getitem__(name) __getattribute__() super() super()[name]

super() 2

super() guide to using super()

tuple([iterable])

tuple (tuple) list, tuple, range

class type(object)
class type(name, bases, dict)

1object object.__class__

isinstance()

3 class name __name__ bases __bases__ dict __dict__ type :

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

3.6 : type.__new__ :class:type

vars([object])

__dict__ __dict__

__dict__ __dict__ types.MappingProxyType

vars() locals() locals locals

zip(*iterables)

i i 1 :

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

zip(*[iter(s)]*n) n n n n

zip() itertools.zip_longest()

zip() * zip :

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
__import__(name, globals=None, locals=None, fromlist=(), level=0)

import (builtins builtins.__import__ ) import (PEP 302 ) __import__() importlib.import_module()

name globals locals fromlist name locals globals import

level 0 () level __import__() ( PEP 328 )

name package.module name () fromlist name

import spam :

spam = __import__('spam', globals(), locals(), [], 0)

import spam.ham :

spam = __import__('spam.ham', globals(), locals(), [], 0)

__import__() import

from spam.ham import eggs, sausage as saus

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

__import__() spam.ham

() importlib.import_module()

3.3 : level ( 0 )

[1] Unix Windows Mac