# Python
# åºæ¬
# ã€ã³ã¹ããŒã«
ãã¡ããåç § (opens new window)
# ããã¥ã¡ã³ã
# çšèª
Python
ããã°ã©ãã³ã°èšèªPythonã€ã³ã¿ããªã¿
Python ã³ãŒããé次å®è¡ããããã°ã©ã (python ã« main é¢æ°ãªã©ã¯ç¡ãïŒIDLE
REPL ç°å¢(shell)ãšãšãã£ã¿ãåãããPython ä»å±ã® IDEPyPI
Python Package IndexããµãŒãããŒãã£ã©ã€ãã©ãªã®éäžåãªããžããªpip
PyPI äžã«å ¬éãããŠããããã±ãŒãžã®ã€ã³ã¹ããŒã«ãŠãŒãã£ãªãã£
# ã¯ãªãŒã
- æååã¯
'
ã§å²ãïŒ'
ã®ãšã¹ã±ãŒããå¿ èŠãªãšãã¯ããã«ã§ã OKïŒ - docstring(heredoc) ã¯
"""
ã§å²ããè€æ°è¡ã«æž¡ã£ãŠæžããã
# ã©ã€ãã©ãª
- ã¢ãžã¥ãŒã«(
os
,datetime
ãªã©)-> é¢æ°ã®éãŸã - ã©ã€ãã©ãª -> ã¢ãžã¥ãŒã«ã®éãŸããç¹ã«ãããã©ã«ãã§çšæãããŠããã©ã€ãã©ãªãæšæºã©ã€ãã©ãªãšåŒã¶ã
import os
import sys
import datetime
sys.platform
sys.version
os.getcwd()
os.environ
os.getenv("home")
datetime.date.today()
# ã¢ãžã¥ãŒã«ã«å®çŸ©ãããŠããé¢æ°ã®äžèŠ§ã衚瀺
dir(os)
# é¢æ°ã®äœ¿ãæ¹ã調ã¹ã
help(os.environ)
# import
import
ã§ã¢ãžã¥ãŒã«å šäœãèªã¿èŸŒãfrom - import
ã§é¢æ°ã ããèªã¿èŸŒã- ã€ã³ããŒãã¯ãã¡ã€ã«ã®ãããã¬ãã«ã§ã®ã¿è¡ããé¢æ°å ã§è¡ããšãåŒã³åºããã³ã«å®è¡ãããåé¡ãçºçããã
import time
time.sleep()
from time import sleep
sleep()
# ã€ã³ãã³ã
- Python ã§ã¯
{}
ãå»æ¢ããã€ã³ãã³ãã§ã³ãŒããããã¯ïŒsuiteïŒãåºå¥ãã - ã³ãŒããããã¯ã®åã«ã¯
:
ãå¿ ãå ¥ã
if a == 1:
do_something()
else:
do_something()
# æåå
# ãªã¹ããç¹å®ã®æååãåºåããšããŠçµåãã
'|'.join(['a','b','c']) # => 'a|b|c'
# æååãç¹å®ã®æåã§åå²ãã
'a|b|c'.split('|') # => ['a', 'b', 'c']
# format by placeholder
%s
str()
ã§åºåãç¹æ®æåã¯ãã®ãŸãŸåºåãããã%r
repr()
ã§åºåãç¹æ®æåã¯ãã ã®æååã«ãšã¹ã±ãŒããããã%d
æŽæ°ã§åºå%1.0f
float ã§åºå
print("I'm going to inject %s text here, and %s text here." % (x, y))
# format by format()
print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))
print('First Object: {a}, Second Object: {b}, Third Object: {c}'.format(
a=1, b='Two', c=12.3))
# format by f-string
a = 1
b = 'wow'
print(f'{a} and {b}') # => '1 and wow'
# Docstring
"""
ã䜿ããš docstring(heredoc)ãæžãã- è€æ°è¡ã«æž¡ã£ãŠæžãããšãã§ããã
# ã³ã¬ã¯ã·ã§ã³
type | description |
---|---|
List | å¯å€é åïŒJS ã® Array çžåœïŒ |
Tuple | äžå€é å |
Dictionary | key-value ã㢠|
Set | ãŠããŒã¯å€ã®éå |
# Boolean
True
ãFalse
ããã¹ã«ã«ã±ãŒã¹ã®ã¿ã
False ãšå€å®ããããã®ã¯äžèšã®ãšããããã以å€ã¯ãã¹ãŠTrue
ã§ããã
0
0.0
''
[]
{}
None
# Date and Times
dt.datetime
--- æ¥ædt.time
--- æédt.timedelta
--- æé
# äœæãã
birthday = dt.datetime(1985,2,13)
# ããã¹ããããŒã¹ããŠäœæãã(p=parse)
birthday = dt.datetime.strptime('24/12/1984', '%d%m%Y)
# ãã©ãŒãããããŠåºåãã(f=format)
birthday.strftime('%d%m%Y')
# Falsy ãªå€ã«é¢ãã泚æ
äžèšã® 2 ã€ã¯ãç°ãªããã®ã§ããã
if cond is not None:
=>None
ã§ãã£ãå Žåã®ã¿äœãããªãif cond:
=>None
,0
,''
,[]
,{}
ã§ãã£ãå Žåã«äœãããªã
äŸãã°ãif somedict['some_key']:
ã ãšãå€ã None ã ã£ãå Žåã ãã§ãªããå€ã 0 ã空æååã®å Žåã«ãå®è¡ãããªãã
ã³ã³ãã£ã·ã§ã³ãæžããšã㯠ãNone 以å€ã® falsy ãªå€(0 ã空æåå)ã§ãã£ãæã«ãäœãããå¿
èŠããããã ãèããfalsy ãªå€ãæŸãå¿
èŠãããã°ãis not None
ã䜿ãããšã
None ã§ç¡ãããšã調ã¹ãåŸã«ãè¿œå ã®å¯Ÿå¿ãå¿ èŠãªå ŽåããããäŸãã°æååãªã空æååã§ãªãããé åãªãèŠçŽ ã 0 ã§ã¯ãªããããªã©ãäŸãã°ããNone ã§ã¯ãªãã空æååã§ããªããæååããä¿éããã«ã¯äžèšã®ããã«ãªãã
if cond is not None and \
type(cond) == str and \
cond != '':
# å¶åŸ¡
# for
python ã®æååã¯ã·ãŒã±ã³ã¹ãªã®ã§å埩åŠçã§ãã
for i in [1,2,3]:
print(i)
for l in "hello":
print(l)
ã€ã³ããã¯ã¹ãååŸããæ¹æ³
for index, word in enumerate(['hello','my','friend']):
print(index, word)
# 0 hello
# 1 my
# 2 friend
# Built-in Functions
å ¬åŒããã¥ã¡ã³ã (opens new window)
# print()
ã³ã³ãœãŒã«çã«æåãåºåãã
print('some string')
print('some string', file=file_object) # ãã¡ã€ã«ã«åºå
print('some string', end='') # è¡æ«ãäœã«ãããïŒããã©ã«ãã¯æ¹è¡ïŒ
print('a', 'b', 'c', sep=',') # => 'a,b,c'
# pprint()
ãªããžã§ã¯ãããããã«ã³ã³ãœãŒã«ã«åºåãã
import pprint
pprint.pprint(some_ugly_dictionary)
# range()
range(çµäºå€)
range(éå§å€, çµäºå€, å»ã¿)
- çµäºå€ã¯çµæã«å«ãŸãªã
range(5) # [0, 1, 2, 3, 4]
range(10, 0, -2) # [10, 8, 6, 4, 2]
# sorted()
sorted()
ã¯ãdict ã® key ããSet ãããœãŒãããããªã¹ãã«ããŠè¿ãã
dict = {'e': 0, 'd': 0, 'c': 0, 'b': 0, 'a': 0}
sorted(dict) # => [a,b,c,d,e]
for key in sorted(dict):
do_something(dict[key])
my_set = {'b','c','a'}
sorted(my_set) # => ['a','b','c']
# list(), set()
list ã set ãäœãã
list('john')
set('hello')
# type()
ã¿ã€ããå€å®ãã
# id()
å€æ°ã®ã¡ã¢ãªã¢ãã¬ã¹è¡šçŸããäžæã®æ°å€ãååŸãã
# str()
ãªããžã§ã¯ããæååã«ããŠè¿ã
# dunder name dunder main
__name__
ãªããžã§ã¯ãã«ã¯ãäžèšã®å€ãå
¥ã
- ãã®ã³ãŒãããPython ã§çŽæ¥å®è¡ããããšã=>
__main__
- ãã®ã³ãŒãããã¢ãžã¥ãŒã«ãšããŠã€ã³ããŒãããããšã=>ã¢ãžã¥ãŒã«å
äžèšã®ã³ãŒãã¯'dunder name dunder main'ãšåŒã°ãããã³ãŒããçŽæ¥å®è¡ãããŠããããåã¯ã€ã³ããŒããããŠãããã調ã¹ãã
if __name__ == '__main__':
do_something()
# ã³ã¬ã¯ã·ã§ã³
# List
- é åºã¯ä¿èšŒããã
# ãªãã©ã«ã§äœæ
numbers = [1, 2, 3, 4, 5]
# ãã«ãã€ã³é¢æ°ã§äœæ
list('john') # => ['j','o','h','n']
# é·ãã調ã¹ã
len(numbers)
# åç
§æž¡ã
new_numbers1 = numbers
# å€æž¡ã
new_numbers2 = numbers.copy()
# æåã®èŠçŽ ãšæåŸã®èŠçŽ
numbers[0]
numbers[-1]
# ãªã¹ãã¡ãœãã
# listã«é¢ããã¡ãœããã衚瀺
help(list)
# è¿œå ãã
numbers.append(6)
# é
åã§è¿œå ãã
numbers.extend([7, 8, 9])
# æå®ããå Žæã«è¿œå ãã
numbers.insert(0, "first-element")
# åé€ãã(ã€ã³ããã¯ã¹å€ã§ã¯ãªããåé€ãããå€èªäœãæž¡ããæåã«èŠã€ãã£ãå€ãåé€ããã)
numbers.remove(2)
# æ«å°Ÿãç¹å®äœçœ®ã®èŠçŽ ãåé€ãã
numbers.pop()
numbers.pop(2)
# ã¹ã©ã€ã¹è¡šèš
[éå§å€, çµäºå€, å»ã¿]
ã®è¡šèšãã¹ã©ã€ã¹è¡šèšãšãããããããçç¥å¯ã- éç Žå£çã«ãªã¹ãã®èŠçŽ ãæœåºã§ãã
- ãªã¹ã以å€ãå«ãããããã·ãŒã±ã³ã¹ããã¹ã©ã€ã¹ã§ãã
numbers[0:5:2]
numbers[::1]
numbers[1::2]
# for ãšãªã¹ã
for ã¯ãªã¹ããã¹ã©ã€ã¹ãç解ã§ããã®ã§ããã®ãŸãŸæž¡ããŠããããšãã§ããã
# Dictionary
- æ§é ãæã€ããŒã¿ã«ã¯ Dictionary(key-value ãã¢)ã䜿ãã
- C++, Java ã§ã¯ããããšåŒã°ããRuby ã§ã¯ããã·ã¥ãšåŒã°ãããã®ã«çžåœã
- é åºã¯ä¿èšŒãããªã
# äœæ
person = {
'name': 'John',
'mail': 'john@john.com',
}
# ããŒã®è¿œå
person['age'] = 33
# for(ããŒã®é ã¯éä¿èšŒ)
for key in some_dictionary:
print(some_dictionary[key])
# ã¡ãœãã
items()
key-value ãã¢ã®ãªã¹ããè¿ã
some_dict = {'e': 0, 'd': 0, 'c': 0, 'b': 0, 'a': 0}
some_dict.items()
# => [('e', 0), ('d', 0), ('c', 0), ('b', 0), ('a', 0)]
# => äžèšã¯dict_itemsãšããç¹æ®ãªå
for key, value in some_dict.items():
# or
for key, value in sorted(some_dict.items()):
setdefault()
ããŒãæªåæåã ã£ãå Žåã«åæåãè¡ã
some_dict.setdefault('somekey', 'somevalue')
# ããã¯äžèšãšç䟡
if 'somekey' not in some_dict:
some_dict['somekey'] = 'somevalue'
pop('ããŒå')
ããŒåã®èŠçŽ ãæãåºããŠè¿ããèŸæžããã¯åé€ããã
# å€ãžã®ã¢ã¯ã»ã¹
- ããŒã®ååšã確å®ã§ããå ŽåïŒãªããã°ãªããªãå ŽåïŒ
dict['somekey']
- ããŒã®ååšãäžç¢ºå®ã§ããå Žå
dict.get('somekey')
=> ããŒãååšããªããã° None ãè¿ãdict.get('somekey', 'default value')
=> ããŒãååšããªããã°default value
ãè¿ã
# ããŒã®ååšç¢ºèªãš None 確èªã¯äž¡æ¹å¿ èŠ
ãæå³ã®ããå€ãã»ãããããŠããå Žåã«éã£ãŠäœãããããããšãã¯ãããŒã®ååšç¢ºèªãšãå€ã None ã§ãããã®ç¢ºèªã¯äž¡æ¹å¿ èŠãšãªãã
ããããŸãã ãã©ãKey ã¯ååšãããã®ã®ãå€ã None ãšããããšã¯ããããã
my_dict = {'i_am_none': None}
# ããŒã®ååšç¢ºèª
bool('i_am_none' in my_dict)
# å€ã®nullãã§ãã¯
bool(my_dict['i_am_none'] is not None)
# ïŒå¿
èŠã«å¿ããŠïŒç©ºæåãªã©ã®ãã§ãã¯
bool(my_dict['i_am_none'] != '')
# åã¯ãããŒã®ååšãã§ãã¯ãçãæ¹æ³
my_dict.get('i_am_none') is not None and \
my_dict.get('i_am_none') != ''
# Set
- Set(éå)ãšã¯ããŠããŒã¯ãªå€ã®ãã€ãŸãã®ããš
- å·®éåãç©éåãåéåãªã©ã®æäœãè¡ãããšãã§ãã
- é åºã¯ä¿èšŒãããªã
# ãªãã©ã«ã§äœæ
vowels1 = {'a', 'e', 'e', 'i', 'o', 'u', 'u'}
# ãã«ãã€ã³é¢æ°ã§äœæ
vowels2 = set('aeeiouu') # => {'u', 'e', 'i', 'o', 'a'}
# çµå union
ãªãªãžãã«ãšæ¯èŒå¯Ÿè±¡ã足ãããã®
original = {'a', 'e', 'i', 'o', 'u'}
u = sorted(original.union(set('hello')))
print(u) # ['a', 'e', 'h', 'i', 'l', 'o', 'u']
# å·®å difference
ãªãªãžãã«ã«ãã£ãŠãæ¯èŒå¯Ÿè±¡ã«ãªããã®
original = {'a', 'e', 'i', 'o', 'u'}
u = sorted(original.difference(set('hello')))
print(u) # ['a', 'i', 'u']
# å ±é intersection
ãªãªãžãã«ã«ããæ¯èŒå¯Ÿè±¡ã«ããããã®
original = {'a', 'e', 'i', 'o', 'u'}
u = sorted(original.intersection(set('hello')))
print(u) # ['e', 'o']
# Tuple
- å€æŽã§ããªããªã¹ãã®ããš
- å€æŽã§ããªããããã«ãäœããªãŒããŒããããåŸããã
- é åºã¯ä¿èšŒããã
# ãªãã©ã«ã§äœã
my_tuple = ('a', 'e', 'i', 'o', 'u')
# èŠçŽ ã1ã€ã®å Žåã¯`,`ãã€ããªããšæååãšããŠå€å®ãããã®ã§æ³šæ
my_tuple = ('single',) # => ('single',)
my_tuple = ('single') # => 'single'
# ãã«ãã€ã³ãã¡ã³ã¯ã·ã§ã³ã§äœã
my_tuple = tuple('aeiou') # => ('a', 'e', 'i', 'o', 'u')
# å å è¡šèš
- ã¡ãªãã
- æžãããã
- æã§ã¯ãªãåŒãšããŠäœ¿ãããšãã§ããïŒãã®ãŸãŸä»£å ¥ã§ããïŒ
- éåžžã® for æãšæ¯èŒããåŠçãæé©åãããŠé«éã«ãªã
- ãªã¹ãå å è¡šèšïŒlistcompïŒãèŸæžå å è¡šèšïŒdictcompïŒãéåå å è¡šèšïŒsetcompïŒããããã¿ãã«å å è¡šèšã¯ååšããªãã
# ãªã¹ãå å è¡šèš
numbers = [1, 2, 3, 4, 5]
big_numbers1 = []
for n in numbers:
big_numbers1.append(n*10)
# äžèšã¯äžèšã®1è¡ãšç䟡
big_numbers2 = [n * 10 for n in numbers]
print(big_numbers1) # [10, 20, 30, 40, 50]
print(big_numbers2) # [10, 20, 30, 40, 50]
# ç¹å®ã®æ¡ä»¶ã«åœãŠã¯ãŸããã®ã ããæãåºãå Žåã¯ifã䜿ã
big_numbers2 = [n * 10 for n in numbers if n == 1]
[]
ã()
ã«çœ®ãæãããšããžã§ãã¬ãŒã¿ã«ãªãããªã¹ãå
å
è¡šèšã¯å
šãŠã®åŠçãçµãããŸã§æ¬¡ã«é²ãŸãªããããžã§ãã¬ãŒã¿ã§ããã° 1 ã€ã®åŠçãçµããããšã«é次å®è¡ãããã
import requests
urls = [
'https://www.google.co.jp',
'https://www.yahoo.co.jp',
'https://www.microsoft.com',
]
for res in [requests.get(u) for u in urls]:
# çµæããã£ãºãã«è¡šç€ºããã
print(res.status_code)
for res in (requests.get(u) for u in urls):
# çµæãæéå·®ã§è¡šç€ºããã
print(res.status_code)
# èŸæžå å è¡šèš
old_dict = {
'key1': 'val1',
'key2': 'val2',
}
new_dict = {f'new_{k}': f'new_{v}' for k, v in old_dict.items()}
print(new_dict) # => {'new_key1': 'new_val1', 'new_key2': 'new_val2'}
# ç¹å®ã®æ¡ä»¶ã«åœãŠã¯ãŸããã®ã ããæãåºãå Žåã¯ifã䜿ã
new_dict = {f'new_{k}': f'new_{v}' for k, v in old_dict.items() if v == 'something'}
# éåå å è¡šèš
èŸæžå
å
è¡šèšã«èŠãããã©:
ããªãããªãã°ããã¯éåå
å
è¡šèšã§ãã
vowels = {'a', 'e', 'i', 'o', 'u'}
phrase = 'hello'
found = {v for v in vowels if v in phrase}
print(found) # => {'e','o'}
# ãã®ä»
# unpacking
ãªã¹ããé åã®èŠçŽ ãå解ããŠæœåºã§ããã
a, b, c = [1, 2, 3]
# 空ã®ããŒã¿æ§é
空㮠set ã¯ç©ºã® dict ãšåºå¥ãã€ããªãã®ã§ãset()
ãšããŠåºåãããã
l = list()
d = dict()
s = set()
t = tuple()
print(l, d, s, t) # => [] {} set() ()
# regex
import re
pattern = '[RL]ock'
re.search(pattern, "Rock'n Roll!") # -> Match Object or None
# ãšã¹ã±ãŒãã«é¢ããè«žåé¡ãåé¿ãããããåžžã«raw stringã䜿ãããš
pattern = r'hello\b world'
# ãã©ã°ã®äœ¿ãæ¹
re.search(pattern,
"Rock'n Roll!",
flags=re.IGNORECASE)
# é¢æ°
# é¢æ°ã®åºæ¬
- Python ã®ã³ãŒãåå©çšã¯ãé¢æ°ã«å§ãŸãé¢æ°ã«çµãã
- é¢æ°ïŒã³ãŒãã«ååãã€ãããã®
- ã¢ãžã¥ãŒã«ïŒé¢æ°ãããã±ãŒãžåãããã®
def some_function(some_argument):
"""é¢æ°ã®èª¬æãããã«æžã"""
# ã³ãŒããããã«ãã
return some_value
# ã¢ãããŒã·ã§ã³
ã¢ãããŒã·ã§ã³ã¯ã人éã楜ã«ã³ãŒããèªããããã«ããããã®ãã®ã Python ã¯ã¢ãããŒã·ã§ã³ãå®å šã«ç¡èŠããã æžãããããšãã£ãŠåãã§ãã¯çãè¡ãããããã§ã¯ãªãã
def search_for_vowels(word: str) -> set:
# ã·ã°ããã£
åŒæ°ã®æ°ãšåã®ããšïŒ
# åŒæ°ã®ããã©ã«ãå€
def search_for_vowels(word: str = "aeiou") -> set:
# ããŒã¯ãŒãåŒæ°ãæž¡ã
ããŒã¯ãŒãã§åŒæ°ãæž¡ããšãé çªãæ°ã«ããã«åŒæ°ãæž¡ãããšãã§ããã
def search_for_vowels(word, letter) -> set:
do_something()
search_for_vowels(letter='letter', word='word')
# èŸæžã§ããŒã¯ãŒãåŒæ°ãæž¡ã
**
ã䜿ããšãdictionary ãå±éããŠãããŒã¯ãŒãåŒæ°ãšããŠæž¡ãäºãã§ããã
def test(name, age):
print(name)
print(age)
person = {
'name': 'John',
'age': 28,
}
test(**person)
# äžèšã¯äžèšãšç䟡
test(name=person['name'], age=person['age'])
# èŸæžã§ããŒã¯ãŒãåŒæ°ãåãåã
**
ã䜿ããšãè€æ°ã®ããŒã¯ãŒãåŒæ°ã dictionary ãšããŠåãåãããšãã§ããã
åŒæ°åã«ã¯kwargs
ã䜿ãã®ãæ
£äŸã
def test(**kwargs):
print(kwargs['name'])
print(kwargs['age'])
test(name='John', age=28)
# ãªã¹ãã§åŒæ°ãæž¡ã
åŒæ°ãæž¡ãéã«*
ã䜿ãããšã§ãé
åã®åèŠçŽ ãåŒæ°ãšããŠæž¡ãããšãã§ãããJS ã®...
ã«çžåœããã
def some_func(a, b, c):
print(a, b, c)
values = [1, 2, 3]
some_func(*values) # => 1,2,3
# ãªã¹ãã§åŒæ°ãåãåã
åŒæ°ãåãåãéã«*
ã䜿ãããšã§ãè€æ°ã®åŒæ°ããªã¹ãïŒæ£ç¢ºã«ã¯ã¿ãã«ïŒãšããŠäžæ¬ã§åãåãããšãã§ãããJS ã®...
ã«çžåœããã
åŒæ°åã«ã¯args
ã䜿ãã®ãæ
£äŸã
def some_func(*args):
pass
some_func() # arg => ()
some_func(1) # arg => (1,)
some_func(1,2) # arg=> (1,2)
# ãžã§ããªã¯ã¹åé¢æ°
ä»»æã®æ°ã®ããããåã®åŒæ°ãåãåãããšã®ã§ããé¢æ°ã®ããšã
def god(*args, **kwargs):
pass
# 以äžã®ãããã®åŒã³åºããValidã§ãã
god()
god(1, 2, 3)
god(a=10, b=20, c=30)
god(1, 2, 3, a=10, b=20, c=30)
# ã¢ãžã¥ãŒã«ã®äœæ
python ãã¢ãžã¥ãŒã«ãæ¢ãå Žæã¯äžèšã® 3 ã€ã®ã¿ã
èªäœã®ã¢ãžã¥ãŒã«ãé
眮ããã®ã§ããã°ãsite-packages
ãå¯äžã®éžæè¢ãšãªãã
- ã«ã¬ã³ããã£ã¬ã¯ããª
site-packages
ãã©ã«ã- æšæºã©ã€ãã©ãª
# å¿ èŠãªãã¡ã€ã«
vsearch.py
ãªã©ïŒã¢ãžã¥ãŒã«æ¬äœïŒREADME.txt
ãšãããã空ã§ã OKsetup.py
ããã±ãŒãžãäœæããããã®ã»ããã¢ãããã¡ã€ã«
# vsearch.py
def say_hello():
print('hello')
# setup.py
import setuptools
setuptools.setup(
name='vsearch', # é
åžãã¡ã€ã«ãšåãååã«ããã®ãæ
£ç¿
version=1.0,
description='my private tool',
author="John Doe",
url='something.com',
py_modules=['vsearch'] # ããã±ãŒãžã«å«ãã.pyã®ãªã¹ã
)
# ããã±ãŒãžãäœæãã
python setup.pyãsdist # dist/MODULE_NAME.tar.gzãšããŠäœæããã
# ããã±ãŒãžãã€ã³ã¹ããŒã«ãã
pip install dist/MODULE_NAME.tar.gz
# ã¹ã³ãŒã
é¢æ°å ããå€éšã®å€æ°ã«ã¢ã¯ã»ã¹ã§ããããã®éãLEGB Rule (local, enclosing functions, global, built-in)ã®é ã«ã¢ã¯ã»ã¹ããã
global_val = 0
def lv1():
lv1_val = 1
def lv2():
lv2_val = 2
print(lv2_val) # local
print(lv1_val) # enclosing funcitons
print(global_val) # global
print(len([1, 2, 3])) # build-in
é¢æ°ã¯ã¹ã³ãŒãã圢æããã®ã§ãå€éšããé¢æ°å ã®å€æ°ã«ã¯ã¢ã¯ã»ã¹ã§ããªãã
original = 1
def test(a):
b = a
c = 1
test(original)
print(a) # error
print(b) # error
print(c) # error
# å ±ææž¡ã
Python ã®åŒæ°æž¡ãã®æ¹æ³ã¯ãå ±ææž¡ã(call by sharing)ãšåŒã¶ã®ãæã劥åœããããã€ãŸãã¯é¢æ°ïŒã¡ãœããïŒã®åŒã³åºãå ãšåŒã³åºãå ã§åããªããžã§ã¯ãããå ±æãããæ¹æ³ã§ããã
Python ã§ã¯å šãŠããªããžã§ã¯ãã§ãããå€æ°ãžä»£å ¥ãããé¢æ°ã®åŒæ°ãžæž¡ããã³ã«å 容ãã³ããŒããŠããã®ã§ã¯ãã³ã»ã³ã¹ã§ããããã®ãããå€æ°ã¯å šãŠããªããžã§ã¯ãã®å®äœãžã®åç §ïŒã¡ã¢ãªã¢ãã¬ã¹ïŒããæ ŒçŽããŠãããé¢æ°ãåŒã³åºããšããããã® ã¡ã¢ãªã¢ãã¬ã¹ãåŒæ°ãšããŠå€æž¡ãããã ããšã§ããªããžã§ã¯ãã¯ãå ±æããããã åç §ã®å€æž¡ããšãèšããã
ãããåŒæ°ãžã®åä»£å ¥ãè¡ããšãå³èŸºã®èšç®çµæïŒãä¿æããŠããã¡ã¢ãªã¢ãã¬ã¹ïŒã巊蟺ã«ä»£å ¥ãããããããã¯ãåŒã³åºãå ãšåŒã³åºãå ã§åããªããžã§ã¯ããå ±æããªããªããããã«ãããä»£å ¥ãè¡ã£ãæã®æåã¯ãè¡šé¢äžã¯å€æž¡ããããŠããããã«èŠããã
ããããå®éã«ã¯ããã§ã¯ç¡ãã®ã§ã åä»£å ¥ãè¡ããŸã§ ã¯ãåŒã³åºãå ã®ãªããžã§ã¯ããæäœããããšãã§ããã
def update(arg):
# å代å
¥ããªããã°ãåŒã³åºãå
ã®å€æ°ãæäœã§ãã
arg.append('new data')
original = [0, 1, 2]
update(original)
print(original) # => [0, 1, 2, 'new data']
def update(arg):
# å代å
¥ãããšãåŒã³åºãå
ã®å€æ°ã¯ãã¯ãæäœã§ããªããªã
arg = ['new data']
original = [0, 1, 2]
update(original)
print(original) # => [0, 1, 2] ãŸãã§å€æž¡ããããŠããããã«èŠããããå®éã¯ç°ãªã
# ãžã§ãã¬ãŒã¿é¢æ°
- äœåããªã¿ãŒã³ã§ããé¢æ°
for
æãªã©ã§é åã®æ¿ããã«æå®ããããšã§ã«ãŒãåŠçã§ãã
def some_func():
sleep(1)
yield 1
sleep(1)
yield 2
sleep(1)
yield 3
for i in some_func():
print(i) # 1 2 3 ã1ç§æ¯ã«è¡šç€ºããã
# lambda åŒ
Expression ãšããŠé¢æ°ãæžãæ¹æ³ã
lambda num: num ** 2
äžèšã¯ JavaScript ã§ããäžèšãšäžç·
(num) => num ** 2;
# Flask
# åºæ¬
pip install Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello()->str:
return 'hello from flask!'
app.run()
# ãã©ã«ãæ§æ
templates
ãã³ãã¬ãŒããã¡ã€ã«ãé 眮ããstatic
éçãã¡ã€ã«ãé 眮ããã/static/**
ã§ã¢ã¯ã»ã¹ããã
# èšå®æ å ±
ã³ã³ãã£ã°èšå®ã¯app.config
ãšããèŸæžã«ä¿æãããšããã
# èšå®æ
app.config['dbconfig'] = {ã}
# å©çšæ
if(app.config['dbconfig'] == 'something'):
# ãã³ãã¬ãŒã
Flask ã«ã¯ jinja2 ãšãããã³ãã¬ãŒããšã³ãžã³ãåãã£ãŠãããããŒã¹ãã³ãã¬ãŒããšãç¶æ¿ãã³ãã¬ãŒãã䜿ãã
base.html
<html>
<head>
<title>{{ the_title }}</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
child.html
{% extends 'base.html' %}
{% block body %}
<h2>{{ the_title }}</h2>
<!-- forã䜿ãã -->
{% for item in the_data %}
<p>{{ item }}</p>
{% endfor %}
<p>some content</p>
{% endblock %}
ã³ã³ãããŒã©
from flask import Flask, render_template, request
@app.route('/child')
def child()->str:
return render_template(
'child.html',
the_title="ã¿ã€ãã«ã§ã",
the_data=['1','2','3'],
)
# ãããã°ã¢ãŒã
ãããã°ã¢ãŒãã§ã¯ãã³ãŒãã«å€æŽãããã°ãµãŒããèªåã§åèµ·åããã
app.run(debug=True)
# ã«ãŒãã£ã³ã°
ã¡ãœããã«ããåŠçãåããæ¹æ³
# methodsã«äœãæžããªããã°GETã«ãªã
@app.route('/')
# some function goes here
@app.route('/user', methods=['GET'])
# some function goes here
@app.route('/user', methods=['POST', 'DELETE'])
# some function goes here
# è€æ°ã®ã«ãŒããäžã€ã®ã³ã³ãããŒã©ã«çŽä»ããããšãã§ãã
@app.route('/')
@app.route('/alias1')
@app.route('/alias2')
# some function goes here
# ã»ãã·ã§ã³
session['ããŒå']
ã§ã»ãã·ã§ã³å€ãèšå®ã»ååŸã§ããã
from flask import Flask, session
app = Flask(__name__)
# Flaskã«ã·ãŒã¯ã¬ããããŒãèšå®ãã
app.secret_key = 'my_secret'
@app.route('/setuser/<user>')
def setuser(user: str) -> str:
session['user'] = user
return 'Userå€ãèšå®: '+session['user']
@app.route('/getuser')
def getuser()->str:
return 'Userå€ã®çŸåšå€: '+session['user']
# ãã©ãŒã ããŒã¿
ãã©ãŒã ããŒã¿ã«ã¢ã¯ã»ã¹ããã«ã¯ãrequest
ãªããžã§ã¯ãã䜿ãã
<input name="letters" />
from flask import Flask, request
@app.route('/search', methods=['POST'])
def search()->str:
request.form['letters']
# ãªãã€ã¬ã¯ã
redirect()
é¢æ°ã䜿ã
from flask import Flask, redirect
@app.route('/')
def top_page():
return redirect('/entry')
# escape()
from flask import excape
escape('<script>danger code</script>')
# ãã¡ã€ã« IO
# open() / close()ã䜿ã
# æžã蟌ã¿
todos = open('todo.txt', 'a')
print('line1', file=todos) # ãã¡ã€ã«ã«åºåãã
print('line2', file=todos)
todos.close()
# èªã¿èŸŒã¿
todos = open('todo.txt') # ããã©ã«ãã¯rã¢ãŒã
for line in todos:
print(line, end='') # éè€ããŠæ¹è¡ãåºåããªã
todos.close()
# ã¢ãŒã
r
èªã¿èŸŒã¿w
æžã蟌ã¿ããã§ã«ååšãããªã空ã«ããa
è¿œå æžã蟌ã¿x
æ°ãããã¡ã€ã«ã«æžã蟌ã¿ããã§ã«ååšãããªã倱æ
+
ãã€ãããšèªã¿æžãã¢ãŒãã«ãªã(x+
ãªã©)
# open() / with()ã䜿ã
with
ã䜿ããšãclose
ã®åŠçãèªåã§è¡ãããã®ã§äŸ¿å©ãwith
ã¯ã³ã³ããã¹ãããããžã¡ã³ãããããã®ãã®ã詳现ã¯åŸè¿°ã
with open('todos.txt') as tasks:
for line in tasks:
do_something()
# or
content = tasks.read() # å
šäœãæååãšããŠäžæ°ã«èªã¿èŸŒã
content = tasks.readline() # 1è¡ã ãèªã¿èŸŒã
content = tasks.readlines() # å
šäœã1è¡1èŠçŽ ã®ãªã¹ããšããŠäžæ°ã«èªã¿èŸŒã
# ããŒã¿ããŒã¹
DB-API
㯠Python ã§ãªã¬ãŒã·ã§ãã«ããŒã¿ããŒã¹ãæ±ãã¢ãžã¥ãŒã«ã«æ±ããããä»æ§ã®ããšã§ããã- ãã®ä»æ§ã«æ²¿ã£ãŠãåãã©ã€ãã¯äœæãããŠããã
Python Code <-> DB-APIïŒã«æºæ ãããã©ã€ãïŒ<-> DB
# æé
# ãã©ã€ãã®ã€ã³ã¹ããŒã«
DB ã«é©å¿ãããã©ã€ãã pip ã§ã€ã³ã¹ããŒã«ãããäŸãã°MySQL ã®å ¬åŒãã©ã€ã (opens new window)ãªã©ã
pip install mysql-connector-python
# DB ã«æ¥ç¶ãã
import mysql.connector
# èšå®ãdictãšããŠäœãïŒä»»æïŒ
dbconfig = {
'host': '127.0.0.1',
'user': 'root',
'password': '123456',
'database': 'vsearchlogDB'
}
# æ¥ç¶ãã
conn = mysql.connector.connect(**dbconfig)
# ã«ãŒãœã«ãååŸããŠãã
cursor = conn.cursor()
# ããŒã¿ãååŸãã
# SQLãäœæïŒæ
£ç¿ãšããŠ_SQLãšããå€æ°ãšãheredocã䜿ãããïŒ
_SQL = """describe log"""
cursor.execute(_SQL)
res = cursor.fetchone() # 1è¡ã ãååŸïŒTupleãè¿ãïŒ
res = cursor.fetchmany(5) # æå®ããè¡æ°ãååŸïŒTupleã®ãªã¹ããè¿ãïŒ
res = cursor.fetchall() # å
šãŠã®è¡ãååŸïŒTupleã®ãªã¹ããè¿ãïŒ
# ããŒã¿ãæ¿å ¥ãã
_SQL = """
insert into log
(phrase, letters, ip, browser_string, results)
values
(%s, %s, %s, %s, %s)
"""
# 第äºåŒæ°ã«Tupleãæž¡ã
cursor.execute(_SQL, ('hitch-hiker', 'xyz', '127.0.0.1', 'Safari', 'set()'))
# 匷å¶çã«æžã蟌ã¿ã確å®ãã
conn.commit()
# DB ãšã®æ¥ç¶ãéãã
cursor.close()
conn.close()
# ã¯ã©ã¹
- Python ã§ã¯ã¯ã©ã¹ã®äœæã¯å¿ é ã§ã¯ãªã
- ãã ãã
with
ã䜿ã£ãŠã³ã³ããã¹ããããžã¡ã³ãïŒååŠçãæ¬åŠçãåŸåŠçïŒãè¡ãã«ã¯ãã¯ã©ã¹ãå¿ é ãšãªã
# ã¯ã©ã¹ã®å®çŸ©ãšã€ã³ã¹ã¿ã³ã¹å
- 空ã®ã¯ã©ã¹ã®å®çŸ©ãšãã€ã³ã¹ã¿ã³ã¹åãè¡ãæ¹æ³ã¯äžèšã®éã
pass
ã¯æ§æçã«æ£ããæå¹ã ããäœãããªãã¹ããŒãã¡ã³ãã§ãã
# 空ã®ã¯ã©ã¹
class CountFromBy:
pass
a = CountFromBy()
b = CountFromBy()
# ã¡ãœããåŒã³åºãã®åã
ã¯ã©ã¹ã€ã³ã¹ã¿ã³ã¹ããã¡ãœãããåŒã³åºãããšããäžèšã®ãããªå€æãè¡ããããã¡ãœããã®å®çŸ©ããdef some_func(self)
ã®ããã« self ãåãã®ã¯ãã®ããã§ããã
a = CountFromBy()
a.increase()
# ããã¯äžèšã«å€æããŠåŒã³åºããã
CountFromBy.increase(a)
# ç¶æ¿
class ChildClass(ParentClass):
pass
# ç¹æ®ã¡ãœãã
- å šãŠã®ã¯ã©ã¹ã¯ãobject ã¯ã©ã¹ãç¶æ¿ããŠãã
- object ã¯ã©ã¹ã¯ããã€ãã®ç¹æ®ã¡ãœãã(dunder)ãæã£ãŠããããããããªãŒããŒã©ã€ãããããšã§ã¯ã©ã¹ã®æ¯ãèããå€ããããšãã§ããã
# __init__
ã€ã³ã¹ã¿ã³ã¹çææã«åŒã³åºããããå±æ§ïŒããããã£ïŒã®åæèšå®ã«äœ¿ãããã
class CountFromBy:
def __init__(self, value, increment):
self.val = value
self.incr = increment
def increase(self):
self.val += self.incr
a = CountFromBy(100, 10)
print(a.val) # 100
a.increase()
a.increase()
a.increase()
print(a.val) # 130
# __repr__
ãªããžã§ã¯ããprint
ãããšããªã©ã«äœ¿ãããããªããžã§ã¯ããè¡šçŸããæååãè¿ãããšã
# super
super ã䜿ã£ãŠç¶æ¿ããã¡ãœããã«å²ã蟌ãããæ¹æ³
def __init__(self, *args, **kwargs):
# do something
super().__init__(*args, **kwargs)
# ã³ã³ããã¹ããããžã¡ã³ããããã³ã«
ååŠç-æ¬åŠç-åŸåŠçãšãããã¿ãŒã³ãäžæãæ±ãããã®ãããã³ã«ã§ããããã®ãããã³ã«ãå®è£
ããã¯ã©ã¹ã§ããã°ãwith
ãšãšãã«äœ¿ãããšãã§ããã
# ã¡ãœãã
# __init__(ãªãã·ã§ã³)
enter ãããåã«è¡ãå¿ èŠã®ããåæåäœæ¥ãè¡ãã
# __enter__
ååŠçãè¡ããwith
ã«å€ãè¿ãããšãã§ããã
# __exit__
åŸåŠçãè¡ãã__init__
ã__enter__
ã倱æããå Žåã«ã¯å®è¡ãããªãã
# ããŒã¿ããŒã¹æäœã®äŸ
# ãããã³ã«ãå®è£ ããã¯ã©ã¹
import mysql.connector
class UseDatabase:
def __init__(self, config: dict) -> None:
self.config = config
def __enter__(self) -> 'cursor':
self.conn = mysql.connector.connect(**self.config)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_value, exc_trace) -> None:
self.conn.commit()
self.cursor.close()
self.conn.close()
# withå
ã§äŸå€ãèµ·ãã£ãå Žåã®åŠç
# (ç¹å®ã®ãšã©ãŒãææ)
if exc_type is RuntimeError:
raise RuntimeError
# (ãã®ä»å
šãŠã®ãšã©ãŒãææ)
elif exc_type:
raise exc_type(exc_value)
# ã¯ã©ã¹ã with ã§äœ¿ã
dbconfig = {
'host': '127.0.0.1',
'user': 'root',
'password': '123456',
'database': 'vsearchlogDB'
}
with UseDatabase(dbconfig) as cursor:
_SQL = """show tables"""
cursor.execute(_SQL)
data = cursor.fetchall()
print(data)
# äŸå€åŠç
__init__
ã__enter__
ã®äžã§èµ·ãã£ããšã©ãŒã¯ãéåžžéãæªè£è¶³ã®ãŸãŸã§ raise ãããã__init__
ã__enter__
ãæåããåŸã«ãããŠãwith
ã®äžã§èµ·ãã£ããšã©ãŒã¯ãäžæŠ__exit__
ã§è£è¶³ãããã第äºåŒæ°ä»¥éã«ãšã©ãŒã®ããŒã¿ãå ¥ãã
# é¢æ°ãã³ã¬ãŒã¿
- æ¢åã®é¢æ°ã®ã³ãŒããå šãå€æŽããã«ãé¢æ°ã®æ¯ãèããå€æŽããããã®ãã®ã
- ã³ãããæžãããã³ãŒãã®èŠéããè¯ãããå¹æãããã
- React ã® HOC ãšåãåã
# ãã³ã¬ãŒã¿ã®ãã³ãã¬ãŒã
from flask import session
from functools import wraps
def check_logged_in(func):
# ãã®ãã³ã¬ãŒã¿ã¯ãæ§ã
ãªåé¡ãèªåã§è§£æ±ºããŠããããããŸããªããšæã
@wraps(func)
def wrapper(*args, **kwargs):
# ååŠç
# ãã³ã¬ãŒããããé¢æ°ãåŒã³åºãå Žåã®åŠçãããã«æžã
# å¿
èŠãªãå€ãè¿ã
if true:
func()
return 'some thing'
# ãã³ã¬ãŒããããé¢æ°ãåŒã³åºããªãå Žåã®åŠçãããã«æžã
# å¿
èŠãªãå€ãè¿ã
return 'another thing'
return wrapper
@check_logged_in
def some_func():
pass
# ãã³ã¬ãŒã¿äœææã®æ³šæ
- ãã³ã¬ãŒã¿ã¯ãã³ã¬ãŒããããé¢æ°ãšåãã·ã°ããã£ãæããªããã°ãªããªãããã£ãŠããžã§ããªã¯ã¹åé¢æ°ã«ããã
wrapper
ãšããååã¯æ £ç¿ãªã®ã§å€ãããªã
# äŸå€åŠç
- Python ã¯ãå®è¡æã«åé¡ãçºçãããš ExceptionïŒäŸå€ïŒãæããã
- äŸå€ã¯éå±€åãããŠãã
- å
šãŠã®äŸå€ã¯
Exception
ã¯ã©ã¹ãç¶æ¿ããŠãã
Built-in Exeptions ã®äžèŠ§ (opens new window)
# try-except
- äŸå€ãçºçããå¯èœæ§ã®ããã³ãŒãã¯
try
ã§å²ã¿ãexcept
ã§ãšã©ãŒãè£è¶³ããã - å
šè£è¶³ãè¡ããšãã¯ãåã«
except:
ãšãããException ã¯ã©ã¹ãšas err
ã䜿ã£ãŠãšã©ãŒãæ£ããå ±åããããš
try:
with open('dummy.txt') as file:
print(file.read())
except FileNotFoundError:
print('ãã¡ã€ã«ãèŠã€ãããŸãã')
except PermissionError:
print('æš©éããããŸãã')
# å
šè£è¶³ããå Žåã¯ãExceptionã§æŸã£ãŠé©åã«åŠçããããš
except Exception as err:
print('æªç¥ã®ãšã©ãŒ: ', err)
# ã«ã¹ã¿ã äŸå€
- ã«ã¹ã¿ã äŸå€ã¯ã
Exception
ã¯ã©ã¹ãç¶æ¿ããããšã§ç°¡åã«äœæã§ããã - æèã«å¿ããŠããå ·äœçãªäŸå€ãå®çŸ©ããããç¹å®ã®äºæã«å¯ãéããäŸå€ãæœè±¡åããå Žåãªã©ã«äœ¿ãã
class MyCustomError(Exceptin):
pass
try:
raise MyCustomError('ã«ã¹ã¿ã ãšã©ãŒã§ã')
except MyCustomError as err:
print(err) # => 'ã«ã¹ã¿ã ãšã©ãŒã§ã'
# ã¹ã¬ãã
- ããéããåŠçãè¡ãéãæ¬ã¹ã¬ããã®åŠçãæ¢ãŸãããããšãªããå¥ã¹ã¬ããã§å®è¡ããæ¹æ³ã
- ä¹±çšãããšèª°ããããã°ã§ããªãã³ãŒãã«ãªãã®ã§æ³šæããã
from threading import Thread
t = Thread(target=some_func, args=(arg1, arg2))
t.start()
print('tãã©ããªã«éããåŠçã§ãããã¯å³æã«å®è¡ããã')
# virtualenv
ä»®æ³ç°å¢ã®äœãæ¹
# ä»®æ³ç°å¢ãäœæããæ©èœã¯ã
# Python v3.3 以éã§ã¯æšæºæ©èœã«åã蟌ãŸããŠããããã
# ã€ã³ã¹ããŒã«ã¯äœæ¥ã¯äžèŠ
# ãããžã§ã¯ããã©ã«ãã«ãããŠäžèšã®ã³ãã³ããå®è¡ãã
# `.venv`ã®éšåã¯å¥œããªååã§OK
python -m venv .venv