# Expert Python Programing

## cheatsheet

1. [mementopython3-english.pdf](https://github.com/Junyangz/Documents/blob/master/assets/mementopython3-english.pdf)
2. [python-cheat-sheet-v1.pdf](https://github.com/Junyangz/Documents/blob/master/assets/python-cheat-sheet-v1.pdf)

## Chapter1

> 待补充

## Chapter2

* 列表推导 \[]
* enumerate
* {推导} -> set集合
* collections类
  1. deque 类似列表(list)的容器，实现了在两端快速添加(append)和弹出(pop)
  2. namedtuple 创建命名元组子类的工厂函数
  3. OrderedDict 字典的子类，保存了他们被添加的顺序
  4. defaultdict
     1. defaultdict类的初始化函数接受一个类型作为参数，当所访问的键不存在的时候，可以实例化一个值作为默认值 `defaultdict(list)`
     2. 该类除了接受类型名称作为初始化函数的参数之外，还可以使用任何不带参数的可调用函数，例如: `defaultdict(lambda: 0)`
  5. [collections官方文档](https://docs.python.org/zh-cn/3/library/collections.html#module-collections)
* 迭代器

  * \_\_next\_\_
  * \_\_iter\_\_
  * yield

  ```python
  def fibonacci():
      a, b = 0, 1
      while True:
          yield b
          a, b = b, a + b
  ```

  * send

  ```python
  import time

  def consumer():
      r = ''
      while True:
          n = yield r
          if not n: return
          print('[CONSUMER] Consuming %s...' % n)
          time.sleep(.1)
          r = '200 OK'
  def produce(c):
      next(c)
      n = 0
      while n < 5:
          n = n + 1
          print('[PRODUCER] Producing %s...' % n)
          r = c.send(n)
          print('[PRODUCER] Consumer return: %s' % r)
      c.close()

  if __name__=='__main__':
      c = consumer()
      produce(c)
  ```
* 装饰器
  * 实现了自己\_\_call\_\_方法的类的实例
  * 语法糖
  * 使用functools模块内置wraps()装饰器打造的装饰器可以保存函数元数据如函数文档字符串
  * 用于 参数检查 缓存 代理 上下文提供者（锁）

    ```python
    from time import time

    def timer(function):
        def wrapper(*args, **kwargs):
            before = time()
            result = function(*args, **kwargs)
            after = time()
            print('Run time is %s' % (after - before))
            return result
        return wrapper

    @timer
    def add_dec(x, y=10):
        return x + y

    @timer
    def sub_dec(x, y=10):
        return x - y
    ```
* with语句

  1. Context Manager

  ```python
  from sqlite3 import connect
  from contextlib import contextmanager

  @contextmanager
  def temptable(cur):
      cur.execute('create table points(x int, y int)')
      print('created table')
      try:
          yield
      finally:
          cur.execute('drop table points')
          print('dropped table')

  with connect('test.db') as conn:
      cur = conn.cursor()
      with temptable(cur):
          cur.execute('insert into points (x, y) values(1, 1)')
          cur.execute('insert into points (x, y) values(1, 2)')
          cur.execute('insert into points (x, y) values(2, 1)')
          cur.execute('insert into points (x, y) values(2, 2)')
          for row in cur.execute("select x, y from points"):
              print(row)
  ```
* **del is the fastest method for removing a key from a Python dictionary**

## Chapter4

> 在Python中，使用二进制按位运算来合并选项是很常见的。使用OR（`|`）运算符可以将多个选项合并到一个整数中，而使用AND（`&`）运算符则可以检查该选项是否在整数中

## Chapter13

* 并发
  1. 多线程multithreading
  2. 多进程multiprocessing
  3. 异步编程
     1. 协程Coroutines
     2. Tasklets
     3. Green trheads
* [refer](https://medium.com/@bfortuner/python-multithreading-vs-multiprocessing-73072ce5600b)

## 异步编程

* async和await


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.junyangz.com/note/expert_python_programing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
