Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ざっとわかるPython

 ざっとわかるPython

hakobe (Yohei Fushii)

November 03, 2017
Tweet

More Decks by hakobe (Yohei Fushii)

Other Decks in Programming

Transcript

  1. Python class Blog(): def __init__(self, id, owner_id, title): self.id =

    id self.owner_id = owner_id self.title = title def is_owned_by(self, user): return user.id == self.owner_id
  2. Python3ͷจࣈྻͷߟ͑ํ • ೖྗΛdecode/ग़ྗΛencode(஌ͬͯΔ΍ ͭ! # 外部からの入力はバイト列 in_bytes = b'\xf0\x9f\x8d\xa3' string

    = in_bytes.decode('utf-8') # バイト列にして外部に出力 out_bytes = string.encode('utf-8')
  3. खݩ؀ڥͷߏங • ݕࡧΩʔϫʔυ: “Python yamaguchi 2017” • ʙ؆୯3εςοϓʙ • pyenvͰॲཧܥΛ͍ΕΔ

    • python -m venv Ͱ؀ڥ੾Γସ͑Δ • pip ͰϥΠϒϥϦΛΠϯετʔϧ͢Δ ͿͬͪΌ͚ॾઆ͋Δ͚ͲखݩͰ͸͜ΕͰշద
  4. flake8 • pycodestyle + pyflake > flake8 enjoy.py enjoy.py:1:1: F401

    'os' imported but unused enjoy.py:3:1: E302 expected 2 blank lines, found 1 enjoy.py:4:5: F841 local variable 'i' is assigned to but never used enjoy.py:9:5: E303 too many blank lines (2)
  5. py.test def inc(x): return x + 1 def test_answer(): assert

    inc(3) == 5 def test_misc(): assert [1,2,3,4], [1,2,3,4] assert isinstance('hello', str)
  6. pytest ͷ࣮ߦ݁Ռ ================== FAILURES =================== _________________ test_answer _________________ def test_answer():

    > assert inc(3) == 5 E assert 4 == 5 E + where 4 = inc(3) test_pyt.py:5: AssertionError ===== 1 failed, 1 passed in 0.06 seconds ======
  7. TestࢧԉϥΠϒϥϦ • freezegun = Test::TimeΈ͍ͨͳ΍ͭ from freezegun import freeze_time import

    datetime def test_time(): with freeze_time("2020-06-06"): assert datetime.datetime.now() == \ datetime.datetime(2020, 6, 6)
  8. Flask from flask import (Flask, request, redirect) web = Flask(__name__)

    @web.route('/<int:entry_id>/edit', methods=['POST']) def edit(): title = request.form['title'] body = request.form['body'] entry = create(title, body) return redirect('/entry/' + entry.id)
  9. σʔλϕʔε • DB͝ͱͷϥΠϒϥϦ: e.g. mysqlclient • API͸PEP 249Ͱඪ४Խ (DBI+DBD) import

    MySQLdb conn = MySQLdb.connect(db='enjoy') with conn.cursor() as cursor: cursor.execute('SELECT UUID_SHORT() as uuid') print(cursor.fetchone().get('uuid'))
  10. ORM࢖Θͣʹૉ๿ʹ΍͍ͬͯ͘ class BlogLoader(): @classmethod def find_by_id(cls, db, blog_id): with db.cursor()

    as cursor: row = cursor.execute(''' SELECT id, owner_id, title FROM blog WHERE id = %s''', (blog_id, ) ).fetchone() return Blog(**row)
  11. ϔϧύΛఆ͍͍ٛͯ͠ײ͡ʹςετ def test_find_by_id(): "EntryLoader.find_by_id() can find a entry by id"

    db = DB() entry = create_entry() found_entry = EntryLoader.find_by_id(db, entry.id) assert isinstance(found_entry, Entry) assert found_entry.id == entry.id
  12. σʔλղੳϥΠϒϥϦ • ͱʹ͔͘ॆ࣮ͯ͠Δ ɹ ͷΩϥʔίϯςϯπ • numpy • scipy •

    scikit-learn • pandas • matplotlib • Jupyter notebook • σʔλղੳ͍ͨ͠ਓ͕ू·͍ͬͯͯ޷॥؀
  13. Numpy import numpy as np m1 = np.array([ [1, 2,

    3], [4, 5, 6], ]) m2 = np.array([ [ 7, 8, 9], [10, 11, 12], ]) m1.dot(m2.T) np.zeros([2, 3]) # array([[ 0., 0., 0.], # [ 0., 0., 0.]]) np.identity(2) # array([[ 1., 0.], # [ 0., 1.]]) np.arange(10).reshape(2,5) # array([[0, 1, 2, 3, 4], # [5, 6, 7, 8, 9]])
  14. Scipy • ࢀߟ: A/Bςετʹ༻͍ΒΕΕΔ౷ܭతݕఆ ख๏ʢϩδοΫʣͷ·ͱΊˍൺֱ import scipy import scipy.stats data

    = [ # click, access [ 150, 500120 ], # A [ 70, 320050 ], # B ] chi2, p, dof, expected = scipy.stats.chi2_contingency(data) print(p) # 0.0339
  15. ࣗ࡞filterؔ਺΁ͷܕ෇͚ from typing import List, Callable, TypeVar T = TypeVar('T')

    def even(n: int) -> bool: return n % 2 == 0 def filter(l: List[T], f: Callable[[T], bool]) -> List[T]: result: List[T] = [] for e in l: if f(e): result.append(e) return result filter(['a', 'b', 'c'], even)
  16. mypy • ܕΞϊςʔγϣϯΛ࢖͏ܕνΣοΧʔ࣮૷ > mypy filter.py filter.py:14: error: Argument 2

    to "filter" has incompatible type Callable[[int], bool]; expected Callable[[str], bool]
  17. asyncio • ࠷ۙ࢖͑Δඪ४ϥΠϒϥϦ (Python 3.4 ~ • ਺͋ΔඇಉظϥΠϒϥϦΛ౷Ұ • ཁ͸AnyEvent(Perl೴

    • ೿ੜϥΠϒϥϦ΋ग़͖ͯͯΔ: e.g. aiohttp • ߏจʹ૊Έࠐ·Εͨ (Python 3.6 ~
  18. asyncio ͱ async/await ߏจ import aiohttp import asyncio async def

    fetch(session, url): with aiohttp.Timeout(10, loop=session.loop): async with session.get(url) as response: return await response.text() async def main(loop): async with aiohttp.ClientSession(loop=loop) as session: html = await fetch(session, 'http://python.org') loop = asyncio.get_event_loop() loop.run_until_complete(main(loop))