Try   HackMD

PyCon TW 2017 Collaborative Talk Notes
Day 3 - R0

How to update this note?

  • Everyone can freely update this note. 任何人都能自由地更新內容。
  • Please respect all the participants and follow our code of conduct during discussion. 討論、記錄時,請遵守大會的行為準則

10:35-11:05
Talk: PyPy's approach to construct domain-specific language runtime

  • Slides:
  • Speaker: TsundereChen(夯) and Jim Huang
    重點提示:
  • Why is Python slow?

    • Interpretation overhead
    • Boxed arithmetic and automatic overflow handling Dynamic dispatch of operations
    • Dynamic lookup of methods and attributes Everything can change on runtime
    • Extreme introspective and reflective capabilities
  • PyPy Translation Toolchain

    • Capable of compiling
    • ®Python Garbage collection
    • Tracing just-in-time (JIT) compiler generator Software
    • transactional memory (STM)
  • PyPy Interpreter

    • written in Rpython
    • Stack-based bytecode interpreter (like JVM)
      • bytecode compiler → generates bytecode
      • bytecode evaluator → interprets bytecode
      • object space → handles operations on objects
  • Parser: source -> lexer -(Token)-> parser -(AST)->

  • Since 2014, PyPy development is diverse:

    • CPython 3 support
    • Improve compatibility with C
    • extensions NumPyPy
    • Multi-threading support
  • Experiment Rep: TsundereChen/bf_to_py

    • Notice that not every program should use PyPy/RPython
    • How to compile PyPy
    • Way to build Interpreter / Translator

延伸議程:

  1. Q
  2. 請問PyPy應該怎麼唸呢?拍拍?皮皮?or?
  3. 建議圖表的部分,縱軸應該從零開始,如果大小差異太大的時候,可以取對數座標表示。

11:15-12:00
Talk: Write Elegant Concurrent Code in Python

Outline

  • Why concurrency?
  • Concurrency is Hard?
  • Communicating Sequential Processes (CSP)
  • Channel-Based Concurrency
  • Concurrent Units
  • CSP vs X

  • Parallel vs Concurrency
    • Parallel 平行:一段時間
    • Concurrency 並行:同一時間
    • *Parallel 包含 Concurrency
  • 如何讓 Concurrency 代碼好看?
    • 通常不會用python解CPU bound的問題,而是解"I/O bound的問題",這個talk討論的也是I/O bound的問題!
    • google後發現套件太多?
      • threading + queue 足以完成大多數 Concurrency 的實作
      • Comment: 這邊的 queue 不是傳統資料結構的queue,而是sync queue,所以是thread-safe
    • Comment: 再複雜一點的也可以再加用process, coroutine, gevent
  • Communicating Sequential Processes(CSP)
    • 描述並行化系統的Formal languge
    • processes communicate with "channel"
    • Go採用CSP而可以寫出簡潔的Concurrency code
    • 用溝通來傳遞 share memory,而不是使用 shared memory 來溝通
    • "Use locks and shard memory to shoot your foot in parellel." - python wiki
  • Channel-Based Concurrency (用 Channel(Queue) 來溝通的 Concurrency)
    • 傳統、非channel-based的方法是不斷從queue拿task,並在完成task後要呼叫task_done通知大家你已經完成task了

    • Python thread = OS thread, but there is evil GIL

    • Daemon Thread

      • 此 daemon 非 unix的daemon => interpreter關掉的時候會自動清掉 unfinished thread
    • 3 layers

      • 查詢atomic方法:盡可能用python內原本就是atomic的方法,不行的話再用channel解 (thread-safe](http://bit.ly/aoperations)
      • 使用channel操作:參考下面範例
      • graph視覺化:用紙筆畫就可以了
  • 範例:爬pycon官網的爬蟲 (3個queue => text_q, url_q, run_q)
    • f1: url-> text via channel
    • f2: text -> url via channel
    • break in the end
    • atomic操作:每個函式都不存取自己以外的東西
    • 用dict來記哪個網址已經造訪過,因為dict是thread-safe
    • 在queue裡放TO_RETURN,其他queue收到就會一起結束,有廣播的效果
    • 除錯建議用印log的方式,可以參考github上的印log的代碼
    • channel的好處彈性擴充:遇到exception可以把exception丟到別的queue
  • Concurrent Units
    • threading.thread
    • @asyncio.coroutine
    • multiprocessing.Process
    • gevent.Greenlet
    • 不要混用,很可怕。你不知道會發生什麼事
    • 根據David所說,Gevent是最快的,asyncio是最慢的 benchmark
  • channel也可以用
    • rabbitMQ
    • redis
    • kafka

與其他方法比較

  • Channel = Lock + message passing
    • Channel 抽象化程度較高
    • 先用Channel設計,在轉換更底層的
  • parallel map
    • 假如你的問題可以用parallel map,就用吧,channel比較低階
  • CSP vs Actor Model
    • 完全等價
    • Actor Model強調

    沒聽清楚 求補充

    • CSP強調 channel
    • Actor model tends to
      • class
      • private state
    • CSP tends to
      • function
      • explicit channel
  • CSP vs Reactive Programming
    • mosky:想到reactive就森77,不知道在紅什麼 ・゚・(´Д⊂ヽ・゚・
    • reactive名詞太多,observable之類的,CSP比較old school大家都會
  • CSP vs MapReduce
    • CSP比較輕量級,有彈性
    • MapReduce需要你去follow他的workflow
  • 總結
    • CSP = Concurrent units + Channels
    • CSP可以避免你踩雷,但Concurrency本身還是個很雷的東西,可能還是會踩到其他的雷
    • 用logging來visualize,以方便debug
    • 別硬用high level的東西,不必要

QA

  • Q: Log Debug好方法
  • A:
    • 用內建的logger, time好用
    • 有user time還有牆上時鐘跑了多久之類的資訊
  • Q: pitfall 例子,channel deadlock
  • A:
    • 傳統上會遇到的問題都會遇到,這是怎麼設計的問題
    • python 3 比較沒lock的問題了

13:00-13:45
Talk: Stranger in a Strange Land

  • Slider:
  • Speaker: Russell Keith-Magee

主軸:用一個語言完成所有事情?(One language to rule them all)

device 為什麼沒有 python?

  • webapps: JavaScripts
  • ios: Object C, Swift
  • android: Java

如果你是個工程師,多語言主義已經成為主流,但如果你不是個工程師只是用特定語言解決特定問題的學者,這可能是個挑戰

Parallelized monolingualism
目的:特定語言 -> API -> 多語言完成的任務

到底什麼是Python?

  • CPython嗎? No

    • GIL 是 Cpython 實作的一部分,不是Python本身的feature
  • 最簡單的Device想法? Embedding CPython

  • Porting CPython

    • 列出目前支援的平台:

      $ ls -d Lib/plat-*

    • 直接編譯CPython成device的Python? No
      • Cross-Compile
    • ctypes: Accessing system libraries
      • ctypes & FFI
      • 用ctype讀取C的.so檔,不需要compile,python可以直接使用C的library
  • 一個新的python(不同platform)面對的問題

    • Parser, Compiler, Eval loop, Std Lib
    • eval loop / std lib 兩者的根據不同provide有不同的解法。
  • ios怎麼處理?

    • 如果是C-based的情況,完全可以用ctypes解決,相對簡單。
  • Android怎麼處理?

    • Cpython不是python,讓python用不同的編譯器(PyPy.js)達成這個目的
    • VOC: parser / compiler
  • Webapps

    • Batavia (用js寫的)
    • 反編譯成 bytecode
      import dis
      dis.dis(some_module)
    • 為什麼webapp不用 Cross-Compile?
      • 太複雜太麻煩,python跟javascript的closure概念不同,我們希望跑的是python,而不只是像python。
    • Webassembly: 還在進行式
  • 個人的comment:

    • 只用單一語言不健康
    • 但我們可以解決它

    http://pybee.org
    aosabook.org

Q. 用python寫的專案能夠被itunes, google play接受嗎?
A. 只要符合不從遠端下載script執行,基本上用python framework寫的是完全能被接受的。

Q. pybee做的東西能夠做出跟原本語言品質相同的專案嗎?
A.
目的如果是特定的(只在某個平台run),基本上是直接邏輯對應轉換。
目的是跨平台多元的,用system API。

13:55-14:25
Talk: enjoy type hinting and its benefits

  • Slider

  • Speaker: masahito

  • 什麼是type hints?

    • 傳統寫法
    • type hints寫法
    • C code寫法
  • type hints的歷史

    • python2
      • 沒有限制函式的arguments跟return values
      • 一些工具會自己填滿它
    • PEP (3107仍然可以繼續寫,但希望未來更多type hints的寫法,詳盡但仍簡潔比簡單但忽略更好)
      • 3107(3.0)
        • free text (沒有限制)
      • 484(3.5)
        • type hints現世
        • 這寫法非必要(python仍保留動態型別特性)
        • 讓code的可讀性,維護性更高

        example: child # 用註解寫型別是bool

        • typing module (484開始的)
          • 讓data structure更好讀

          a: List[int] = [1,2,3]

          • NamedTuple
      • 526(3.6)
        • 向下相容
        • 讓code可讀性更高(直接寫型別在變數上)

        example: child: bool

#3107 def greeting(xxx): return "hello" + xxx #484 待補 #526 待補
  • 取得 type hints 的資訊
c: Car = Car() #有一個Car的Object c.__annotations__
  • 我們從type hints得到的Benefit
    • Code Style: Simple, Explicit
    • Code Completion
      • Editor
      • PyCharm
    • 編譯器能夠透過type hints提供輔助訊息輔助開發者開發
    • mypy
    • CI
      • 可以在CI系統上跑mypy

Q:是否真的用type hints預防了什麼問題?
??????%&*$^*&#^$#*^$#$

14:35-15:20
Talk: 千百種面對 PDF 的方法

  • Slider:
  • Speaker: 廖偉涵 Adrian Liaw

adrianliaw是一個馬來西亞律師,找不到的話可以找adrianliaw2000
高二在家自學鋼琴小帥哥

  • 剖析PDF

    • 結論:能不處理就不要處理,真的很麻煩,用keyin就好
    • 先想想看大眾向的格式資料
      • JSON:直覺的dictionary格式
      • CSV:輕易的當data frame處理
      • XML/HTML:有結構化的資料
      • 共通點:有架構、資訊明確,設計就是讓機器可讀的
    • PDF?
      • 投影片看不清楚沒關係,黑人問號比較重要
      • 用regex抓不到東西,沒有巢狀結構
      • portable: 在哪台電腦看起來都一樣
      • 指令是用來指定哪個東西要放在哪個位置
      • 常見物件:char, rect, line
      • pdf格式可參考 http://simpopdf.com
  • PDFMINER (一個不難找到的python用的pdf parsing套件)

    • 著重文字擷取、線條沒有處理非常好
    1. parse (PDFParser, PDFDocument):圖像的架構
    2. intepret(PDFInterpreter, PDFDevice):產生Object
      • 重點是PDFDevice,處理各種parse後的資訊擷取(文字面效果較佳)
      • get_pages(open('xxx.pdf')) 產生一個generator
    • 好處
      • 都python寫的
      • pdf2txt
      • lazy-loading
    • 壞處
      • 但只支援python2,需要裝pdfminer.six才支援python3
      • 沒什麼有用的文件,常需要讀code
      • 需要重複寫很多boilerplate
      • 架構複雜難以理解
      • 向量圖形的資訊不容易抓取
  • 初始化步驟:

resources = PDFResourceManager() device = PDFPageAggregator(resources) interpreter = PDFPageInterpreter(resources, device) # Then...extract
  • Poppler(C++ library)
    • Reducing Problem: 先把pdf轉成xml/html/json,再截取我們要的內容
    • 沒有比較好用的python架接API
  • pdftohtml

    $ pdftohtml -xml <input.pdf>

  • pdftocairo

    $ pdftocairo -svg <input.pdf>

    • 原始碼裡面會看不到讀到的文字,但SVG顯示時看得到文字。通常可以用他來得到每個物件的座標位置,再用pdfminer讀實際的文字內容
    • 轉換成svg後,再用svgpathtools
      • 文件超少
      • 每個圖形視為一個path,用虛數代表x,y座標
from svgpathtools import svg2paths paths, attribs = svg2paths("graphics.svg") # Then...extract
  • why so many choices?
    • not choices, it's a combination
    • 結果常常會不如預期

Q. 你怎麼處理PDF的?(遇過同行內,被視為同的東西的情況)
A. 先抓出輪廓,再抓輪廓內的內容