Share
Embed
Transcript
51 slides
-
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 -
ࠓͷΰʔϧ: Pythonͷงғؾ͕ͬ͟ͱΘ͔Δ ˒ ։ൃڥ ˒ Web։ൃ ˒ σʔλੳ ˒
ݴޠͷਐԽ ˒ ίϛϡχςΟ -
Python3 Unicodeจࣈྻ 1. ৗʹ use utf8; ͞ΕΔΑ͏ʹͳͬͨ(Perl 2. จࣈྻͱόΠτྻΛ·ͥΔͱྫ֎ʹͳΔ
• ݕࡧΩʔϫʔυ: “python3 unicode ͳͥ” -
Python3ͷจࣈྻͷߟ͑ํ • ೖྗΛdecode/ग़ྗΛencode(ͬͯΔ ͭ! # 外部からの入力はバイト列 in_bytes = b'\xf0\x9f\x8d\xa3' string
= in_bytes.decode('utf-8') # バイト列にして外部に出力 out_bytes = string.encode('utf-8') -
खݩڥͷߏங • ݕࡧΩʔϫʔυ: “Python yamaguchi 2017” • ʙ؆୯3εςοϓʙ • pyenvͰॲཧܥΛ͍ΕΔ
• python -m venv ͰڥΓସ͑Δ • pip ͰϥΠϒϥϦΛΠϯετʔϧ͢Δ ͿͬͪΌ͚ॾઆ͋Δ͚ͲखݩͰ͜ΕͰշద -
ϥΠϒϥϦ • ඪ४ϥΠϒϥϦ • Battery Included ํࣜͰॆ࣮ • https://docs.python.jp/3/library/ •
CPANతͳͭ = PyPI • ඪ४ͷpip ίϚϯυͰΠϯετʔϧͰ͖Δ -
ΤσΟλ • ͍͍ͩͨPythonαϙʔτ͕͋ͬͯ҆৺ • ྑ͍IDE͋Δ: PyCharm • ࠷ۙࣗVisual Studio CodeΛͬͯΔ
• linterิ͕͙͑ͯ͢ศར -
Linter • flake8Λ͍͍͑ͩͨOK • ͨΒLinterతϥΠϒϥϦ͕ଟ͍ • pycodestyle, pydocstyle, pyflake, flake8,
hacking … • autopep8 ॻ͖͑ͯ͘ΕΔͭ͋Δ -
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) -
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) -
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 ====== -
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) -
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) -
WSGI • αʔόͱΞϓϦέʔγϣϯؒͷϓϩτίϧ • PSGIͷܑ͓͞Μ def app(environ, start_response): start_response( '200
OK', [('Content-Type', 'text/plain')] ) yield b'Hello World\n’ -
HTTPαʔό • جຊ prefork worker model • uWSGIthread͑ΔͬΆ͍? V84(* ࠷ۙྲྀߦΓͰଟػೳ
(VOJDPSO 3VCZͷΞϨ༝དྷͰγϯϓϧ -
σʔλϕʔε • DB͝ͱͷϥΠϒϥϦ: e.g. mysqlclient • APIPEP 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')) -
ബ͍Web AppͷߏΛࢼͯ͠Έͨ • hakobe/hakoblog-python • ബ͍WebϑϨʔϜϫʔΫ (Flask) • ORMͳ͠ (mysqlclientΛʹ͏)
• ServiceϨΠϠ • ςϯϓϨʔτΤϯδϯ Jinja2 -
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) -
ϔϧύΛఆ͍͍ٛͯ͠ײ͡ʹςετ 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 -
σʔλղੳϥΠϒϥϦ • ͱʹ͔͘ॆ࣮ͯ͠Δ ɹ ͷΩϥʔίϯςϯπ • numpy • scipy •
scikit-learn • pandas • matplotlib • Jupyter notebook • σʔλղੳ͍ͨ͠ਓ͕ू·͍ͬͯͯ॥ -
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]]) -
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 -
scikit-learn • σʔλੳ/σʔλϚΠχϯά ϥΠϒϥϦू • ධՁͷͨΊͷศརάοζ • ͰػցֶशΤϯδχΞͷؾʹͳΕΔ from sklearn
import svm svc = svm.SVC() svc.fit(X, y) svc.predict(Xtest) -
matplotlib • σϑΝΫτͷάϥϑඳըϥΠϒϥϦ • ͍͍ͩͨͳΜͰͰ͖ͯศར • API͕Ή͍ͣͷͰସϥΠϒϥϦ͕ຄڵ͍ͯ͠ Δͱ͔ • ݕࡧΩʔϫʔυ:
“matplotlib alternative” -
Jupyter notebook • REPLͷ͓Խ͚(ݩIPython) • ίʔυΛ࣮ߦͨ͠Γ࣮ߦ݁ՌΛදࣔͨ͠Γ આ໌Λॻ͍ͨΓͰ͖ΔWebΞϓϦ • ΊͪΌͪ͘Όࢼߦࡨޡ͍͢͠ •
ͳΊ͚ͯͨͲ࣮ࡍ͔ͭ͏ͱ͛͢ʔࢼߦࡨޡ͠ ͍͢… -
ࣗ࡞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) -
mypy • ܕΞϊςʔγϣϯΛ͏ܕνΣοΧʔ࣮ > mypy filter.py filter.py:14: error: Argument 2
to "filter" has incompatible type Callable[[int], bool]; expected Callable[[str], bool] -
asyncio • ࠷ۙ͑Δඪ४ϥΠϒϥϦ (Python 3.4 ~ • ͋ΔඇಉظϥΠϒϥϦΛ౷Ұ • ཁAnyEvent(Perl
• ੜϥΠϒϥϦग़͖ͯͯΔ: e.g. aiohttp • ߏจʹΈࠐ·Εͨ (Python 3.6 ~ -
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))