Skip to content

Instantly share code, notes, and snippets.

@Airtnp
Created August 1, 2017 14:49
Show Gist options
  • Save Airtnp/e73749217493d098e78a6d6460b3d475 to your computer and use it in GitHub Desktop.
Save Airtnp/e73749217493d098e78a6d6460b3d475 to your computer and use it in GitHub Desktop.
Python Idiom (raw has better view)

Python Idioms

#

  • *args : tuple
  • **kwargs : dict
  • [[]]*10 创建对同一个列表5次引用的列表
  • __slots__: compile-time restrict attribute
  • @/__matmul__ in py3

A

  • abc module : virtual (abstact) base class
    • register
    • subclasshook
    • @abstractmethod (compare to @classmethod, @staticmethod, slots)
  • async/await
    • async with
      • __aenter__/__aexit__/__aiter__
    • async def
  • analyzer
    • inspect module
      • signature
    • ast module
    • parser module
    • pdb module
    • dis module (python bytecode)

B

  • bound
    • unbound

C

  • c3 algorithm
    • 查找: instance.dict -> Parentest.dict -> instance.class.dict (instance.class.__mro__顺序)
  • contextlib module
    • enter + exit => try + yield
  • collection module
    • namedtuple
    • OrderDict
    • heapq
  • coroutine : yield (from)
  • callback / delegate
  • closure
    • nonlocal
  • compare
    • in Python 2, you can < compare anything to anything.
  • ctypes
  • comprehension
    • list
    • dict
      • print {i : chr(65+i) for i in range(4)} -> {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}

D

  • descriptor
    • get
    • set
    • delete
  • decorator (AOP)
  • duck typing
  • Database ORM
  • 单例
    • new
    • 模块常量
  • Decimal
  • Default parameter
    • 默认列表只在函数被定义的那一刻创建一次 def func(l = [])
  • del 循环引用 => gc 不工作

E

  • Exception
    • rethrow: raise ... from ...
    • sys.exceptionhook

F

  • functools module
    • @lru_cache
    • total_ordering : #include <boost/operator.hpp>
    • partial : bind
    • fp method
      • reduce/map/filter
    • singleddispatch (overload without type hinting)
    • wrapper
      • @wraps : save name, doc
  • faulthandler in py3
  • format
    • align/padding/named-variable(Formatted string literals)
    • F-string
      • name = "Test" f"My app name is {name}."

G

  • get : descriptor
  • getattr : class/base property
  • getattribute : instance property
  • get -> getattr -> getattribute
  • generator : yield/next
    • GeneratorExit

H

I

  • iterator
    • iter : return self
    • next : return data | StopIteration
  • itertools modules : just like #include <numeric>
  • import hacking
    • module q
    • sys.modules[name] = Class
    • module/package/loader
    • path/file/name
    • all/version
    • PEP 302
    • importlib
    • _temp = import('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
  • init_subclass

J

K

  • Keyword only arguments
    • def foo(*, arg1=1, arg2=None) in python3 (force named params)

L

  • logging module
  • LEGB
    • locals->enclosing->globals->builtins
      • assignment will make variables local (copy) (use global/nonlocal to prevent)

M

  • mro (method resolution order)
  • metaclass <-> class <-> instance
    • prepare
    • new/init
    • call
  • mutable / immutuble
    • reference problem
  • magic method
    • xxx => xxx(class)
  • Mixin
  • method wrapper (slot wrapper)

N

O

  • os module

P

  • PyObject
  • PyType
  • @property (public type name {get; set;})
    • .getter
    • .setter
    • __property: private => _classname__property
    • _property: protect => _property

Q

R

  • re module: regex (no unicode property \p{CN})
    • lookaround ?= ?! ?<= ?<!
    • capture ?:
    • name ?P ?P=name
    • greedy .*?
    • comment ?#
    • \number group
    • Regular expression -> NFA (POSIX NFA) -> DFA(BNF)
  • Resize strategy
    • 8->32->...-> >50000 x2->x2 (set, dict)
    • (size+1 >> 3) + (size+1 < 9 ? 3 : 6) (list, 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...) (\approx 1.125)

S

  • science modules
    • numpy
    • sympy
    • matplotlib
  • sys module
    • sys._getframe()
      • | f_back # 上一个栈帧对象(谁调用自己)
      • | f_builtins # 内置名字空间
      • | f_locals # local名字空间
      • | f_globals # 全局名字空间
      • | f_code # 帧指向的 codeObject对象
      • | f_cellvars # 内部闭包使用的freevar
      • | f_freevars # 闭包引用的freevar
      • | f_localsplus # 局部变量 + cell对象 + free对象 + 运行时栈
        • | co_name # code block的名字, 通常是类名或者函数名 /* string (name, for reference) */
        • | co_names # code block中所有的名字 /* list of strings (names used) */
    • sys.getrefcount()
  • super()
    • new-style class
    • just call the next function in the mro links (generated by C3)
    • will continue call if super() in base classes
  • small integer pool : -5~257
  • Recursive stack overflow
    • trampoline
    • continuation-pass-style (callback)
    • raise exception and pass value
  • str (py3)
    • wchar_t
    • utf-8 bytes (unicodedata_db) : UCS-1/UCS-2/UCS-4
  • star expression
    • _1, *_, _5 = [1, 2, 3, 4, 5]
    • _1, _2, * = range(10)

T

  • typing module
    • List
    • Callable[..., ReturnType]
    • Generics
      • Mapping
      • Sequence
      • TypeVar (template )
      • Type (Covariant, inheritance)
      • Optional
      • Union (Variant)
    • Iterable
    • Iterator
    • Reversible
    • Supports__
    • collectIons.abc
    • ContextManager
    • Any
    • annotations (dict of type hinting)
  • type module
    • get frame/global vars
    • co_xxx
  • type<->object relation
  • type hinting
  • tuple
    • (1, 2, [3, 4])[2] += [1, 2] -> error + (1, 2, [1, 2, 3, 4])
    • check is after the assignment

U

  • User data-type
    • inheritance from
    • avoid c-api (list/dict) error

V

W

  • warnings module

X

Y

Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment