こしごぇ(B)

旧:http://d.hatena.ne.jp/koshigoeb/

Python 再入門(3.1)

参考書籍

パーフェクトPython (PERFECT SERIES 5)

パーフェクトPython (PERFECT SERIES 5)

The Zen of Python

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

Python の基本

  • __name__ 変数
  • input()
  • print()
  • docstring
  • global, nonlocal
  • 定数はない
  • GC はリファレンスカウンタ式

型とリテラル

  • 論理型: True, False
  • 数値型
    • int
      • Python3 では Python2 の long と同等
      • Python3 では 整数同士の除算の結果に浮動小数点数を使う
    • complex
    • モジュール: math, cmath, numbers, fractions, decimal
  • シーケンス
    • 文字列(str)、バイト列(bytes)
      • Python3 ではスクリプトファイルは UTF-8 で記述されている事を想定している
      • immutable
    • バイト配列型(bytearray)
      • mutable なバイト列
    • リスト(lists)
      • mutable
    • タプル(tuples)
      • immutable
  • 集合(set)
    • ユニークなリストで順序は保持されない
    • add, remove
    • イテレーション
    • union
    • intersection
    • difference, symmetric_difference
    • issubset, isuperset, disjoint
  • 辞書型
    • 存在しないキーを指定すると例外
    • 順序は保証されない
  • None 型

制御構文

条件文

    • None
    • False
    • ゼロとして認識出来る数値型(0, 0.0, 0j, ...)
    • 空のシーケンス([], (), ...)
    • 空のマップ型({})
    • 空のセット(set())
    • __nonzero__ メソッドが実装されているクラスで False を返すもの
    • __len__ メソッドが実装されているクラスで 0 を返すもの
if x:
    ...
elif y:
    ...
else:
    ...
  • and, or, not

比較演算子

  • >, <, ==, is

ループ

  • for i in [1, 2, 3]:
    • else
      • ループが終わったとき、ループしなかったときに実行される
      • break でぬけたときは実行されない
  • while
    • else
      • for 同様

リスト内包表記

  • 簡潔に記述できる
  • 実行コストを軽減できる

リスト内包表記

>>> [x ** 2 for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

セット内包表記

>>> {x ** 2 for x in range(1, 11)}
set([64, 1, 36, 100, 81, 9, 16, 49, 25, 4])

辞書内包表記

>>> {x * 2 : x ** 2 for x in range(1, 11)}
{2: 1, 4: 4, 6: 9, 8: 16, 10: 25, 12: 36, 14: 49, 16: 64, 18: 81, 20: 100}

例外処理

  • try, except
>>> try:
...     10/0
... except Exception as e:
...     print e
...
integer division or modulo by zero
  • else ** try ブロックで例外が発生しなかった場合に実行される
  • finally ** try ブロックで例外が発生したかにかかわらず実行される
>>> def test(x):
...     try:
...         10 / x
...     except Exception as e:
...         print x
...     else:
...         print 'success'
...     finally:
...         print 'fin.'
...
>>> test(1)
success
fin.
>>> test(0)
0
fin.
  • raise
  • assert
  • 例外オブジェクトの __context__

with

with open('test.txt', 'a') as f:
    f.write('test')
  • with ブロックに入るときにコンテキストマネージャ(ContextManager)の __enter__ メソッドを呼び出し、出るときに __exit__ メソッドを呼び出す
  • contextlib の closing を使うと close してくれる
from contextlib import closing
with closing(open('test.txt', 'a')) as f:
    f.write('test')
  • open の場合はそれ自体がコンテキストマネージャとして使えるため、closing を使う必要は無い
  • ジェネレータと contextlib の contextmanager デコレータを使う方法もある

Python 再入門(2)

ポイントをつかんでおこうと思って選んだ本だけど、これはまだ手をつけるのは早かった模様。かろうじてCっぽいプログラムが書ける程度の記憶しか残っていないので、色々と思い出してから改めて。

参考書籍

エキスパートPythonプログラミング

エキスパートPythonプログラミング

構文ベストプラクティス

リスト内包表記

>>> [i for i in range(10) if i % 2 == 0 and i != 4]
[0, 2, 6, 8]

イテレータとジェネレータ

  • iter
  • next
  • __iter__
  • yield
  • send
  • throw
  • close
  • コルーチン
    • トランポリン
    • PyPI multitask
  • ジェネレータ式
  • itertools モジュール
    • islice, tee, groupy

デコレータ

  • @classmethod, @staticmethod
  • 引数チェック
  • キャッシュ
  • プロキシ
  • コンテキストプロバイダ

with と contextlib

  • __enter__
  • __exit__
  • contextlib モジュール
    • contextmanager, closing, nested

Python 再入門(1)

かなり昔に『初めてのPython』を読んだっきり、結局使わずにきたPythonに再入門。 とりあえず、環境を整えつつ感じをつかむ。

参考書籍

Pythonプロフェッショナルプログラミング

Pythonプロフェッショナルプログラミング

開発環境

pyenv を使う。

$ pyenv install 2.7.5
$ pyenv virtualenv 2.7.5 2.7.5-test
$ pyenv virtualenvs
$ pyenv local 2.7.5-test
$ pyenv versions

補助ツールなど。

  • IPython: インタラクティブシェル拡張
  • PYTHONSTARTUP 環境変数
  • pep8: コーディング規約
  • pyflakes: 構文チェック
  • pdb: デバッガ

余りに手探りで Emacs の設定が面倒に感じたので、PyCharm を使ってみる事に。継続するか Emacs に戻るかは使い心地次第。

Web アプリを作る

フレームワーク Flask を使って Web アプリケーションを作ってみる。

$ pyenv virtualenv 2.7.5 2.7.5-ppp-guestbook
$ pyenv local 2.7.5-ppp-guestbook
$ pip install Flask
$ charm .

PyCharm のプロジェクト設定で ~/.pyenv/versions/2.7.5-ppp-guestbook/bin/python を使う様にする。

(面倒くさいので略)

ドキュメントを書く

Sphinx が有名。

ソースコードの docstring に reST でドキュメントを記述しておくと、Sphinxsphinx-apidoc コマンドを使って API ドキュメントが生成できる様になる。

$ pip install sphinx
$ pyenv rehash
$ sphinx-apidoc -F -o docs src
$ cd docs
$ make html
$ open _build/html/index.html

テスト

標準ライブラリの unittest や nose を使ってユニットテストを行う。 モックを使いたい場合は mock というライブラリが利用可能。 WebTest というライブラリを使うと、擬似的な HTTP リクエストを送るなどといった形で WSGI アプリの機能テストを行える。

デプロイ

Fabric を使うと、複数のリモートサーバをまとめて操作する事ができる。

ニートからサラリーマンにジョブチェンジ

ついに、週明けからサラリーマンにジョブチェンジです。

絶望溢れる就職活動をどうにか乗り切って、やっとつかんだ試用期間。

支給されるmacのためにも全力でがんばらなきゃね。

Top-level-browsing-context って?

『HTTPの教科書』を読んでいて、X-Frame-OptionsヘッダのSAMEORIGINの説明に「Top-level-browsing-contextが一致した場合のみ許可」と書かれていた。

Same origin policy でいう origin が一致していたらという事だと思っていたんだけど、Top-level-browsing-contextという表現を使う必要があるのはどういうことだろうか。Frameの入れ子とかになっていた場合にどのoriginと比べるのか分からなくなるから、トップレベルのドキュメントコンテキストと比べるんだという感じの意味かな?

X-Frame-Options に関するドキュメントって何を参考にしたら良いんだろうか?以下のドラフトでいいのかな?

SAMEORIGIN A browser receiving content with this header MUST NOT display this content in any frame from a page of different origin than the content itself. If a browser or plugin can not reliably determine whether the origin of the content and the frame have the same origin, this MUST be treated as "DENY". (Please note that current implementations may vary on the interpretation of this criteria: In some it only allows to be framed if the origin of the top-level browsing-context is identical, in other it compares with to the origin of the framing page.)

http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-01

Top-level-browsing-context ってのは、HTML5の用語という事で良いのかな?

The browsing context with no parent browsing context is the top-level browsing context of all the browsing contexts nested within it (either directly or indirectly through other nested browsing contexts).

http://www.w3.org/TR/2010/WD-html5-20100304/browsers.html#top-level-browsing-context

結局、互いのTop-level-browsing-contextのoriginが一致したら許可しまっせという感じかな?

『HTTPの教科書』 読んだ

Amazon で入荷待ちが解消された様なので購入。

HTTPの教科書

HTTPの教科書

とりあえず、自分でRFC読んだりWebブラウザとかHTTPサーバを実装したりした事がある新人は別として、HTTPに詳しくない様な新人は買って読んどくと良いと思う。一通り理解しておかないと、404 Not Found を知らせるページを 200 OK で返したりして、怖い大人に dis られたりするだろうし。

web系のプログラマとして1,2年も働いてれば、たぶん本書に書かれている前半部分は既知だろうと思う。が、RFCに目を通したことがない様な人にとっては、既知だとしてもバラバラに学んできたことを体系的に学べて良いと思う。40代過ぎて中学の歴史の教科書を読み返す的な?違うか。

第5章の5.1で説明されている、HTTP/1.1のHostヘッダを使ったバーチャルホストの話だけど、「HTTP/1.1では、1つのHTTPサーバで複数のWebサイトを立ち上げることができる」というのは正確には「1つのIPアドレスで複数のドメイン」という事で良いのかな?IPベースのバーチャルホストってのもあると思うけど、その話は敢えてしてないのかも。細かい話ですね。

Cache-Controlヘッダに結構なページを使ってくれているのは個人的に助かる。他にも、色々とヘッダについて説明してくれているのもうれしい。X-Frame-Options, X-XSS-Protection, DNT, P3Pも書かれてる。 X-Frame-OptionsのSAMEORIGINはbrowsing contextというものに左右されるという事だけど、これはSame origin policyでいうOriginと同一のものだと考えて良いのだろうか?スキームとホストとポート番号だっけ?browsing contextはHTMLの用語?あと、MDNで見かけたALLOW-FROMはまだこれからってことかな?

という事で、ざっくり流し読んだ感じではあるけど、上手いことまとめられててちょうどよい教科書だと思う。

ようやくひとごこち

先週末の大失態でしばらくはウド鈴木のごとくえづきが止まらず、送別会で癒やされつつ、ふて寝を経てなんとかひとごこち。

送別会でもらった UP Band とかいうやつの使い方が分からず、全然使えてないわけですが、どうやら電池切れの疑いが。とりあえず、付属のUSBケーブルでパソコンにつないで充電中。

寄せ書きで号泣して足下が水浸しになるという大ハプニングもあったとかなかったとか。