◆ ビルトイン関数のまとめ
  ◆ 同じような系統でまとめ
  ◆ サンプルコード

Python のドキュメントってそこまで見やすくなくて もう少し見やすければなと思うことが多いです
ページ内の目次つけたり サンプル増やしたり 分け方だったり

特に慣れないうちによく見るビルトイン関数のページは 全部 1 ページにまとめて書いてる上に 50 音順に並べたもので どういう系統とかでまとまってないので見づらいです
用途ごとにまとめた上でサンプルコードと結果を載せてくれたらいいのにと思います
そんなわけで自分でまとめてみました

((注意))
長くなってまとめるのが面倒で 1 年以上放置してた記事なので 一部情報が古いかもしれません(気づいたところは修正してますけど)
breakpoint に触れてるのでたぶん書き始めたのは 3.7 がでた頃だった気がします

((参考))
https://docs.python.org/ja/3/library/functions.html
https://docs.python.org/ja/3/reference/datamodel.html

一覧

for x in vars(__builtins__).keys():
if not x.startswith("_") and str.islower(x[0]):
print(x)
abs
all
any
ascii
bin
breakpoint
callable
chr
compile
delattr
dir
divmod
eval
exec
format
getattr
globals
hasattr
hash
hex
id
input
isinstance
issubclass
iter
len
locals
max
min
next
oct
ord
pow
print
repr
round
setattr
sorted
sum
vars
bool
memoryview
bytearray
bytes
classmethod
complex
dict
enumerate
filter
float
frozenset
property
int
list
map
object
range
reversed
set
slice
staticmethod
str
super
tuple
type
zip
open
quit
exit
copyright
credits
license
help

大文字から始まるのは True, None, Ellipsis などの値や Error, Exception 系なので除外
ドキュメントのリストにある __import__ が上のリストにないのは _ から始まるの項目を除外表示してるから

ドキュメントのリストと比べると quit, exit, copyright, credits, license が追加されてる
これらと help は自動でロードされる site パッケージ中で builtins に追加される
https://github.com/python/cpython/blob/v3.7.7/Lib/site.py#L353-L394
https://github.com/python/cpython/blob/v3.7.7/Lib/_sitebuiltins.py

python コマンドに -S オプションをつけて site の初期化をしないようにするとこれらは builtins に含まれなくなる

分類

同系統の処理で分けたもの
分け方は同系統のものをまとめていって そのグループにあってそうな名前をつけただけで特別な意味はないです

リスト・イテレータ系

all()全部の要素が True か
any()要素のどれかが True か
filter()各要素に関数を適用して結果が True のものだけ残す
map()各要素に関数を適用した結果で置き換える
sum()各要素の値を合計する
sorted()ソート済みのリストを作る
reversed()反転するイテレータを作る
zip()(直列じゃなくて)並列に結合する
len()長さを返す
next()イテレータの次の要素を取得

数学系

abs()絶対値
max()最大値
min()最小値
round()四捨五入(偶数丸め)
pow()冪乗
divmod()割り算と余り

オブジェクト系

hasattr()attribute があるか
getattr()attribute を取得
setattr()attribute をセット
delattr()attribute を消す
classmethod()第一引数にクラスオブジェクトが渡されるメソッドを作る
staticmethod()第一引数に暗黙的に引数が渡されないメソッドを作る
property()getter/setter/deleter が用意された属性を作る
isinstance()インスタンスが指定クラスのインスタンスか
issubclass()クラスが指定クラスのサブクラスか
super()属性検索を指定クラスの親から行うオブジェクトを作る

コンストラクタ系

int()int 型作る
float()float 型作る
complex()複素数型作る
bool()真偽値型作る
str()文字列型作る
list()リスト型作る
tuple()タプル型作る
dict()ディクショナリ型作る
set()セット型作る
frozenset()変更できないセット型作る
object()オブジェクト型作る
bytes()bytes 型作る
bytearray()bytearray 型作る

コンストラクタ系 2

iter()イテレータ型作る
enumerate()enumerate 型作る
range()range 型作る
slice()slice 型作る
memoryview()memoryview 型作る

変換系

bin()0b 付き 2 進数の文字列に変換
oct()0o 付き 8 進数の文字列に変換
hex()0x 付き 16 進数の文字列に変換
chr()文字コードから文字に変換
ord()文字から文字コードに変換
repr()オブジェクトをテキストに変換
ascii()repr の文字列の非 ASCII 文字をエスケープ表現にしたものに変換
format()指定のフォーマットに変換

内部データ系

vars()オブジェクトの __dict__ を取得
dir()オブジェクトの属性リストを取得
type()オブジェクトの型を取得 / 動的な class 定義
callable()呼び出し可能かどうかを取得
id()オブジェクトを表す id を取得
hash()ハッシュ値を取得
globals()グローバル変数一覧のディクショナリを取得
locals()ローカル変数一覧のディクショナリを取得

開発補助系

help()ヘルプの表示
breakpoint()debugger の起動

入出力系

input()標準入力から 1 行入力
print()値を文字列化して標準出力などへ出力
open()ファイルを開く

実行系

eval()式実行
exec()文実行
compile()ソースコード文字列をコードオブジェクトに変換

モジュール

__import__()動的インポート

終了系

exit()プログラムの終了
quit()プログラムの終了



コンストラクタの 2 つは他系統には入ってないクラス
一応 zip, filter, staticmethod, property などもクラス
コンストラクタ 2 はクラスだけど 単体の値じゃなくて元になる値が必要なもの

サンプル

all

全部が True になれば True
False になる値がひとつでもあると False
JavaScript の every みたいにコールバック関数の指定はできない

all([1, 2, 3])
# True
all([1, 2, 0])
# False

map やリスト内包表記で変換したものに使う

all([x > 1 for x in [1, 2, 3]])
# False

any

all の反対でどれかが True になれば True

any([1, 2, 0])
# True
any([0, 0, 0])
# False

any([x > 1 for x in [1, 2, 3]])
# True

filter

コールバック関数を使って要素をフィルタ
返り値は filter 型なので list などで使わないと処理されない

f = filter(lambda x: x > 0, [1, -1, 0])
# <filter at 0x18f4de44b00>

list(f)
# [1]

lambda でその場に書けるような条件ならリスト内包表記の if で十分

[x for x in [1, -1, 0] if x > 0]
# [1]

map

コールバック関数を使って要素を変換
返り値は map 型なので list などを使わないと処理されない

f = map(lambda x: x + 1, [1, 2, 3])
# <map at 0x18f4ddf3ba8>

list(f)
# [2, 3, 4]

lambda でその場に書けるような条件ならリスト内包表記で十分

[x + 1 for x in [1, 2, 3]]
# [2, 3, 4]

sum

要素の合計を求める
初期値の指定ができる

sum([1, 2, 3])
# 6
sum([1.1, 2.2, 3.3], 10)
# 16.6

初期値に __add__ を持つ値を指定すると reduce 風に使える

class A:
def __init__(self, sep):
self.sep = sep
self.value = None

def __add__(self, v):
if self.value is None:
self.value = str(v)
else:
self.value += self.sep + str(v)
return self

print(sum(["a", "b", "c"], A("_")).value)
# a_b_c

sorted

ソート済みのリストの新しいリストを取得できる
元のものは壊さない

sorted([10, 3, 2, 6, -1, 0, 5, 9])
# [-1, 0, 2, 3, 5, 6, 9, 10]

a = [1, 3, 2]
sorted(a, reverse=True)
# [3, 2, 1]

a
# [1, 3, 2]

reversed

並びを反転させる
返り値は list_reverseiterator 型なので list 使わないと処理されない

r = reversed([1, 2, 3])
r
# <list_reverseiterator at 0x18f4dd0cb38>

list(r)
# [3, 2, 1]

__reversed__ メソッドで好きな値を返せる

class A(list):
def __reversed__(self):
return [1, 2, 3]

reversed(A())
# [1, 2, 3]

zip

複数の iterable オブジェクトを結合
後ろにつなげるのじゃなくて 同じ◯番目の要素をタプルでまとめる
一番短いのに合わされる
捨てられるのがなければ再 zip で元通り

返り値は zip 型なので list などを使わないと処理されない

z = zip([1, 2], [3, 4, 5], [6, 7])
z
# <zip at 0x18f4e160088>

list(z)
# [(1, 3, 6), (2, 4, 7)]

len

長さを持つオブジェクトの長さを取得

len([1, 2])
# 2

len((1, 2, 3, 4))
# 4

len("foo")
# 3

class A:
def __len__(self):
return 4

len(A())
# 4

__len__ メソッドは int 型を返さないといけない

next

iterator の次の要素を取得
__next__ メソッドがあればよい
list などの iterable な値は iter で iterator 化必要
次がない場合はデフォルト値を 2 つめの引数で指定してないとエラー

next(iter([1, 2]))
# 1

next(iter([]), 2)
# 2

class A:
def __next__(self):
return 3

next(A())
# 3

abs

絶対値

abs(1)
# 1
abs(-1.2)
# 1.2

class A:
def __abs__(self):
return 2

abs(A())
# 2

__abs__ メソッドの返り値で負の数や文字列を返してもエラーにはならない

max

iterable か可変長引数から最大の値を取得

max(1, 2, 3)
# 3
max([1, 2, 3])
# 3

min

iterable か可変長引数から最小の値を取得

min(1, 2, 3)
# 1
min([1, 2, 3])
# 1

round

指定の桁で丸め(偶数丸め)

round(1.23)
# 1
round(1.23, 1)
# 1.2
round(91.23, -1)
# 90

class A:
def __round__(self, d):
return d

round(A(), 1)
# 1
round(A(), 100)
# 100

__round__ メソッドの返り値で 数値以外でも返せる

pow

x ** y もしくは x ** y % z を計算

pow(2, 3)
# 8
pow(2, 3, 3)
# 2

class A:
def __pow__(self, a, b):
return f"{a} ** {b} = {a**b}"

pow(A(), 2, 3)
# '2 ** 3 = 8'

__pow__ メソッドの返り値で 数値以外でも返せる

divmod

割り算した商と余りを取得

divmod(11, 2)
# (5, 1)

class A:
def __divmod__(self, a):
return 1

def __rdivmod__(self, a):
return 2

divmod(A(), 10)
# 1
divmod(10, A())
# 2
divmod(A(), A())
# 1

__divmod__ メソッドの返り値で タプルじゃなくてもいい

hasattr

attribute を持ってるか

class A:
def x(self):
pass

def __init__(self):
self.y = 10

z = 20

hasattr(A(), "w")
# False
hasattr(A(), "x")
# True
hasattr(A(), "y")
# True
hasattr(A(), "z")
# True

getattr

attribute の取り出し
__getattr__ と __getattribute__ メソッドが実行される
__getattr__ は attribute があれば呼び出されない

class A:
x = 1
def __init__(self):
self.y = 2

def z(self):
return 3

def __getattr__(self, name):
return "getattr " + name

a = A()
getattr(a, "x")
# 1
getattr(a, "y")
# 2
getattr(a, "z")
# <bound method A.z of <__main__.A object at 0x0000020635A6A208>>
getattr(a, "w")
# 'getattr w'
a.a
# 'getattr a'
class A:
x = 1

def __init__(self):
self.y = 2

def z(self):
return 3

def __getattribute__(self, name):
return "getattribute " + name

a = A()
getattr(a, "x")
# 'getattribute x'
getattr(a, "y")
# 'getattribute y'
getattr(a, "z")
# 'getattribute z'
getattr(a, "w")
# 'getattribute w'
a.a
# 'getattribute a'

setattr

attribute のセット
文じゃなく式なので lambda で使える

class A: pass

a = A()
setattr(a, "x", 10)
a.x
# 10
class A:
def __setattr__(self, name, value):
print("setattr " + name, value)

a = A()
setattr(a, "x", 10)
# setattr x 10
a.y = True
# setattr y True

delattr

attribute の削除
文じゃなく式なので lambda で使える

class A:
x = 1

def __init__(self):
self.y = 2

def z(self):
return 3

a = A()
a.x
# 1
a.y
# 2
a.z
# <bound method A.z of <__main__.A object at 0x0000020635E92278>>

delattr(a, "y")
a.y
# 'A' object has no attribute 'y'

delattr(a, "x")
# AttributeError: x
delattr(a, "z")
# AttributeError: z

x や z は A の attribute なので A に対して削除必要

class A:
def __init__(self):
self.x = 1
self.y = 2

def __delattr__(self, name):
print("delete " + name)

a = A()
delattr(a, "x")
# delete x
del a.y
# delete y
a.x
# 1
a.y
# 2

classmethod

1つ目の引数に自動でクラスオブジェクトが入って呼び出されるメソッドにする

class A:
@classmethod
def fn(cls, a, b):
return (cls, a, b)

A.fn(1, 2)
# (__main__.A, 1, 2)

a = A()
a.fn(10, 20)
# (__main__.A, 10, 20)

A.fn(1, 2)[0] is A
# True

staticmethod

1 つ目の引数に自動でインスタンスやクラスオブジェクトを渡さないメソッドにする

class A:
@staticmethod
def fn(a, b):
return (a, b)

A.fn(1, 2)
# (1, 2)

a = A()
a.fn(10, 20)
# (10, 20)

property

getter, setter, deleter を作る

class A:
def __init__(self):
self._value = 10

value = property(
lambda s: s._value,
lambda s, v: setattr(s, "_value", v),
lambda s: delattr(s, "_value")
)

a = A()
a.value
# 10
a.value = 100
a.value
# 100
del a.value
a.value
# AttributeError: 'A' object has no attribute '_value'
class A:
value = property(
lambda s: print(s, "getter called"),
lambda s, v: print(s, "setter called"),
lambda s: print(s, "deleter called"),
)

a = A()
a.value
# <__main__.A object at 0x00000136105BF9B0> getter called
a.value = 100
# <__main__.A object at 0x00000136105BF9B0> setter called
del a.value
# <__main__.A object at 0x00000136105BF9B0> deleter called

isinstance

クラスのインスタンスかどうか

class A: pass
class B: pass
class C: pass

isinstance(A(), A)
# True

isinstance(A(), (A, B))
# True

isinstance(A(), (B, C))
# False

メタクラスの __instancecheck__ メソッドで判定を変えられる

class M(type):
def __instancecheck__(self, instance):
return True

class A(metaclass=M): pass

isinstance(10, A)
# True

issubclass

クラスがサブクラスかどうか

class A: pass
class B(A): pass

issubclass(B, A)
# True

issubclass(A, B)
# False

a = A()
b = B()
issubclass(type(b), type(a))
# True

メタクラスの __subclasscheck__ メソッドで判定を変えられる

class M(type):
def __subclasscheck__(self, subclass):
return True

class A(metaclass=M): pass
class B: pass

issubclass(B, A)
# True

super

親クラスのメソッドを呼び出すためのオブジェクトを取得

class A: pass
class B(A): pass

super(A)
# <super: __main__.A, None>
super(A, A)
# <super: __main__.A, __main__.A>
super(A, A())
# <super: __main__.A, <__main__.A at 0x13610c5e7b8>>
super(A, B)
# <super: __main__.A, __main__.B>
super(A, B())
# <super: __main__.A, <__main__.B at 0x136105d3780>>
super(B, A)
# TypeError
super(B, A())
# TypeError

class A:
def x(self):
return 1

class B(A):
def x(self):
return 2

b = B()
b.x()
# 2
super(B, b).x()
# 1

class A:
def x(self):
return 1

class B(A):
def x(self):
return 2

class C(B):
def x(self):
return 3

c = C()
super(C, c).x()
# 2
super(B, c).x()
# 1

クラス内部でなら引数を省略できる

class A:
def x(self):
return 1

class B(A):
def x(self):
return super().x()

b = B()
b.x()
# 1

多重継承すると

class A1:
def x(self):
return "A1"

class A2(A1):
def x(self):
return "A2"

class B1:
def x(self):
return "B1"

class B2(B1):
def x(self):
return "B2"

class C(A2, B2):
def x(self):
return "C"

super(C, C()).x()
# 'A2'
super(A2, C()).x()
# 'A1'
super(A1, C()).x()
# 'B2'
super(B2, C()).x()
# 'B1'

int

int 型作る

int()
# 0
int(10)
# 10
int(1.2)
# 1
int("-3")
# -3

class A:
def __int__(self):
return 9
int(A())
# 9

class A:
def __trunc__(self):
return 8
int(A())
# 8

__int__, __trunc__ メソッドの返り値
int 型を返さないといけない
float を返しても変換されない

16 進数文字列のパースにも使う

int("ffff", 16)
# 65535
int("1001", 2)
# 9

float

float 型作る

float()
# 0.0
float(1.2)
# 1.2
float("-2.3")
# -2.3
float("1e3")
# 1000.0

class A:
def __float__(self):
return 1.234

float(A())
# 1.234

__float__ メソッドの返り値
float 型を返さないといけない
int でも変換されない

complex

complex 型作る

complex()
# 0j
complex(10)
# (10+0j)
complex("-1.23")
# (-1.23+0j)
complex("4+9j")
# (4+9j)
complex("-3j")
# -3j
complex(1, 2)
# (1+2j)

class A:
def __complex__(self):
return 1+2j

complex(A())
# (1+2j)

__complex__ メソッドの返り値
complex 型を返さないといけない

bool

bool 型作る

bool()
# False
bool(1)
# True
bool(0)
# False
bool("0")
# True
bool("")
# False
bool([])
# False
bool({})
# False
bool([0])
# True
class A: pass
bool(A)
# True
bool(A())
# True
bool(...)
# True
bool(None)
# False
class B:
def __bool__(self):
return False
bool(B())
# False

__bool__ メソッドの返り値
bool 型を返さないといけない

str

str 型作る

str()
# ''
str(10)
# '10'
str(True)
# 'True'
str(None)
# 'None'
str(...)
# 'Ellipsis'
str({1, 2})
# '{1, 2}'
str(["a", False])
# "['a', False]"
str(b"a")
# "b'a'"

class A: pass
str(A)
# "<class '__main__.A'>"
str(A())
# '<__main__.A object at 0x00000240AD4FD6A0>'

class B:
def __str__(self):
return "aa"
str(B())
# 'aa'

__str__ メソッドの返り値
str 型を返さないといけない

list

list 型作る
iterable な値を list に変換

list()
# []
list(1)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
list("abc")
# ['a', 'b', 'c']
list({"a", "b"})
# ['a', 'b']
list(map(lambda x: x+1, [1, 2]))
# [2, 3]
list({"a": "A", "b": "B"})
# ['a', 'b']

tuple

tuple 型作る

tuple()
# ()
tuple(1)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
tuple("abc")
# ('a', 'b', 'c')
tuple([1, 2])
# (1, 2)
tuple({"a": 1, "b": 2})
# ('a', 'b')

dict

dict 型作る

dict()
# {}
dict(((1, 2), (3, 4)))
# {1: 2, 3: 4}
dict(["ab", "cd"])
# {'a': 'b', 'c': 'd'}
dict(a=1, b=True, c=None, d="")
# {'a': 1, 'b': True, 'c': None, 'd': ''}

set

set 型作る

set()
# set()
set(1)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
set("abcd")
# {'a', 'c', 'd', 'b'}
set([1, 2, 3, 4])
# {1, 2, 3, 4}

frozenset

frozenset 型作る
set の更新できない版
更新関係のメソッドがない

set(dir(set())) - set(dir(frozenset()))
# {'update', 'pop', 'intersection_update', 'clear', '__iand__',
# '__ior__', '__ixor__', 'difference_update', '__isub__',
# 'symmetric_difference_update', 'remove', 'discard', 'add'}

object

object 型作る

object()
# <object object at 0x7feddb3161e0>

引数取らないし __dict__ ないから属性も持てない
用途は一意な参照の値を作るくらい?

bytes

bytes 型作る
イミュータブル

bytes()
# b''
bytes(10)
# b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
bytes("abc", encoding="utf-8")
# b'abc'
bytes.fromhex("616263")
# b'abc'

bytearray

bytearray 型作る
ミュータブル

bytearray()
# bytearray(b'')
bytearray(10)
# bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray("a", encoding="utf-8")
# bytearray(b'a')
bytearray.fromhex("616263")
# bytearray(b'abc')
bytearray(b"a")
# bytearray(b'a')

iter

iterator 型作る

iter([])
# <list_iterator object at 0x00A13340>
iter(())
# <tuple_iterator object at 0x00A13250>
iter({})
# <dict_keyiterator object at 0x00A1D820>
iter(set())
# <set_iterator object at 0x00A12BC8>
iter(range(1))
# <range_iterator object at 0x00A13338>

引数必須

iter()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: iter expected at least 1 arguments, got 0

__iter__ メソッドの返り値
iterator (__next__ メソッド持ち) を返さないといけない

class A:
def __iter__(self):
return B()

class B:
def __next__(self):
raise StopIteration()

iter(A())
# <__main__.B at 0x240ad61d198>

enumerate

enumerate 型作る
iterable の要素のそれぞれを連番をつけたタプルにする
連番の初期値は 2 つめの引数で指定

enumerate()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: enumerate() missing required argument 'iterable' (pos 1)
enumerate([1, 2])
# <enumerate object at 0x7ffb35855ca8>
list(enumerate((1, 2, 3)))
# [(0, 1), (1, 2), (2, 3)]
list(enumerate({"a", "b"}))
# [(0, 'a'), (1, 'b')]
list(enumerate({"a": 10, "b": 20}))
# [(0, 'a'), (1, 'b')]
list(enumerate([0, 1, 2], 101))
# [(101, 0), (102, 1), (103, 2)]

range

range 型作る

range()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: range expected 1 arguments, got 0
range(3)
# range(0, 3)
range(2, 10, 3)
# range(2, 10, 3)
list(range(3))
# [0, 1, 2]
list(range(2, 7))
# [2, 3, 4, 5, 6]
list(range(2, 10, 3))
# [2, 5, 8]

slice

slice 型作る

slice()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: slice expected at least 1 arguments, got 0
slice(3)
# slice(None, 3, None)
slice(1, 10)
# slice(1, 10, None)
slice(2, 10, 3)
# slice(2, 10, 3)
list(range(100))[slice(1, 100, 10)]
# [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]

memoryview

memory 型を返す

memoryview()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: memoryview() missing required argument 'object' (pos 1)
memoryview(b"foo")
# <memory at 0x7ffb359354c8>
memoryview(b"foo").obj
# b'foo'
memoryview(bytearray(b"foo")).obj
# bytearray(b'foo')
memoryview(b"foo").readonly
# True
memoryview(bytearray(b"foo")).readonly
# False

bin

0b から始まる 2 進数文字列に変換する

bin(0)
# '0b0'
bin(1)
# '0b1'
bin(2)
# '0b10'
bin()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: bin() takes exactly one argument (0 given)
bin(3)
# '0b11'
bin(0b111100001111)
# '0b111100001111'

oct

0o から始まる 8 進数文字列に変換する

oct(4)
# '0o4'
oct(10)
# '0o12'
oct(1024)
# '0o2000'
oct(0o12345)
# '0o12345'

hex

0x から始まる 16 進数文字列に変換する

hex(4)
# '0x4'
hex(12)
# '0xc'
hex(10)
# '0xa'
hex(16)
# '0x10'
hex(1024)
# '0x400'
hex(0xabcd)
# '0xabcd'

chr

Unicode コードポイントを文字に変換する

chr(65)
# 'A'
chr(0x61)
# 'a'
chr(12354)
# 'あ'

ord

文字を Unicode コードポイントに変換する

ord("A")
# 65
ord("あ")
# 12354

repr

オブジェクトを文字列で表す

repr("abc123\nあいうえお!!")
# "'abc123\\nあいうえお!!'"

class A:
def __repr__(self):
return "aあ"
repr(A())
# 'aあ'

__repr__ メソッドの返り値
str 型を返さないといけない

ascii

repr の文字列の非 ASCII をエスケープした文字列を取得

ascii("abc123\nあいうえお!!")
# "'abc123\\n\\u3042\\u3044\\u3046\\u3048\\u304a!\\uff01'"

class A:
def __repr__(self):
return "aあ"
ascii(A())
# 'a\\u3042'

format

指定フォーマットに変換

format(1024, "x")
# '400'
format(0.123, "%")
# '12.300000%'
format(123456789, "g")
# '1.23457e+08'

class A:
def __format__(self, x):
return f"A: {x}"
format(A(), "abcd")
# 'A: abcd'

__format__ メソッドの返り値
str 型を返さないといけない

vars

__dict__ を取得
__dict__ を持たないオブジェクトはエラー

vars(object())
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: vars() argument must have __dict__ attribute

vars(dict())
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: vars() argument must have __dict__ attribute

vars("123")
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: vars() argument must have __dict__ attribute
vars(str)
# mappingproxy({'__add__': <slot wrapper '__add__' of 'str' objects>,
# '__contains__': <slot wrapper '__contains__' of 'str' objects>,
# '__doc__': "str(object='') -> str\n"
# 'str(bytes_or_buffer[, encoding[, errors]]) -> str\n'
# '\n'
# 'Create a new string object from the given object. If '
# 'encoding or\n'
# 'errors is specified, then the object must expose a '
# 'data buffer\n'
# 'that will be decoded using the given encoding and '
# 'error handler.\n'
# 'Otherwise, returns the result of object.__str__() '
# '(if defined)\n'
# 'or repr(object).\n'
# 'encoding defaults to sys.getdefaultencoding().\n'
# "errors defaults to 'strict'.",
# '__eq__': <slot wrapper '__eq__' of 'str' objects>,
# '__format__': <method '__format__' of 'str' objects>,
#(長いので略)
# 'zfill': <method 'zfill' of 'str' objects>})
class A: pass
vars(A)
# mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>,
# '__doc__': None,
# '__module__': '__main__',
# '__weakref__': <attribute '__weakref__' of 'A' objects>})

a = A()
vars(a)
# {}

a.x = 1
a.y = 2
v = vars(a)
v
# {'x': 1, 'y': 2}

v["y"] = 23
a.y
# 23
class B:
def __init__(self):
self.x = 10

y = 20

def z(self): pass

vars(B)
# mappingproxy({'__module__': '__main__',
# '__init__': <function __main__.B.__init__(self)>,
# 'y': 20,
# 'z': <function __main__.B.z(self)>,
# '__dict__': <attribute '__dict__' of 'B' objects>,
# '__weakref__': <attribute '__weakref__' of 'B' objects>,
# '__doc__': None})

vars(B())
# {'x': 10}

__init__ で代入するインスタンス固有のデータがインスタンスの __dict__ にある
クラス全体のものはクラスオブジェクトの __dict__ にある

dir

attribute の名前の list を取得
vars では見えないものも見える

dir(1)
# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__',
# '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__',
# '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__',
# '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__',
# '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__',
# '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__',
# '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__',
# '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__',
# '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__',
# '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__',
# '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',
# 'numerator', 'real', 'to_bytes']

class A:
def __init__(self):
self.x = 10

y = 20

def z(self): pass

dir(A)
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
# '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
# '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
# '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
# '__str__', '__subclasshook__', '__weakref__', 'y', 'z']

dir(A())
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
# '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
# '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
# '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
# '__str__', '__subclasshook__', '__weakref__', 'x', 'y', 'z']

class B:
def __dir__(self):
return [1, 2, 3]

dir(B())
# [1, 2, 3]

__dir__ メソッドの返り値
iterable 型を返さないといけない
文字列だと 1 文字ずつの list 化される
list はソート済みになるので それぞれの要素は 「<」 演算子が使えないといけない
int と str を混ぜるとエラー

class C:
def __lt__(self, x):
return False

class D(C): pass
class E(C): pass
class F(C): pass

class G:
def __dir__(self):
return [C(), F(), D(), E()]

dir(G())
# [<__main__.C object at 0x00673310>,
# <__main__.F object at 0x00673370>,
# <__main__.D object at 0x00673388>,
# <__main__.E object at 0x006733A0>]

type

オブジェクトの型を取得

type(1)
# <class 'int'>
type(1) == int
# True
type(int)
# <class 'type'>
type(str)
# <class 'type'>
class A: pass
type(A)
# <class 'type'>
type(A())
# <class '__main__.A'>
type(A()) == A
# True
type(type)
# <class 'type'>

class 構文の代わり

A = type("ABC", (), {"a": 10, "b": lambda self: self.a})
A
# <class '__main__.ABC'>
a = A()
a.a
# 10
a.b
# <bound method <lambda> of <__main__.ABC object at 0x7f09f797b828>>
a.b()
# 10
A.a
# 10

callable

呼び出し可能かどうか

callable(lambda:1)
# True

def fn(): pass
callable(fn)
# True

class Class: pass
callable(Class)
# True
callable(Class())
# False

class Class2:
def __call__(self): pass

callable(Class2())
# True

id

オブジェクトの id を習得

id(1)
# 1527769008
id(1)
# 1527769008
id("ab")
# 6303392
id("a" + "b")
# 6303392
id({})
# 6133112
id({})
# 6133112
id(object())
# 4089288
id(object())
# 4088000
a = {}
b = {}
id(a)
# 6133112
id(b)
# 6133152

hash

オブジェクトのハッシュ値を習得

hash(1)
# 1
hash(123)
# 123
hash(999)
# 999
hash("1")
# 6796202901105847829
hash("1")
# 6796202901105847829
hash("abc")
# 2099571838025763916
hash(10 ** 128)
# 1745057488448534351

一緒になったりならなかったりする

class A: pass
hash(A())
# -2147290327
hash(A())
# -2147290315
class A: pass
hash(A())
# 598818
hash(A())
# 598818
hash(A())
# 598818
hash(A())
# 598818

class A:
def __hash__(self):
return 12345

hash(A())
#12345

__hash__ の返り値
int 型を返さないといけない

globals

グローバル変数一覧の dict を取得

globals()
# {'__name__': '__main__', '__doc__': None, '__package__': None,
# '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0035E898>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
# '__file__': 'py.py', '__cached__': None}
a = 1
def f(): pass
class c: pass
globals()
# {'__name__': '__main__', '__doc__': None, '__package__': None,
# '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x002CE898>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
# '__file__': 'py.py', '__cached__': None, 'a': 1, 'f': <function f at 0x005DA190>, 'c': <class '__main__.c'>}

locals

ローカル変数一覧の dict を取得

globals() is locals()
# True

def fn(x):
print(locals())
y = 1
print(locals())

fn(10)
# {'x': 10}
# {'x': 10, 'y': 1}

help

ヘルプの表示
引数なしだとヘルプ用のプロンプトに変わる
画面に入り切らないと more や less での表示

>>> class A: pass
...
>>> help(A)
Help on class A in module __main__:

class A(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

>>> help()

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>

breakpoint

breakpoint を設定する

>>> code = """
... val = 1
... print(val)
... breakpoint()
... print("val is", val)
... """
>>> exec(code)
1
> <string>(5)<module>()->None
(Pdb) h

Documented commands (type help <topic>):
========================================
EOF c d h list q rv undisplay
a cl debug help ll quit s unt
alias clear disable ignore longlist r source until
args commands display interact n restart step up
b condition down j next return tbreak w
break cont enable jump p retval u whatis
bt continue exit l pp run unalias where

Miscellaneous help topics:
==========================
exec pdb

(Pdb) val
1
(Pdb) val = 100
(Pdb) c
val is 100

VSCode などの GUI でも有効
行に breakpoint 設定したときみたいに breakpoint 関数実行直後で停止して GUI から操作できる
JavaScript の debugger みたいなもの

input

標準入力から 1 行受け取り

>>> input()
123
'123'
>>> input("input text> ")
input text> aaa
'aaa'

print

標準出力へ出力

print(123)
# 123

class A: pass
class B:
def __str__(self):
return "abc"

print(A())
# <__main__.A object at 0x000001E248138208>

print(B())
# abc

__str__ メソッドの返り値
str 型を返さないといけない

可変長引数で 各引数を文字列化したものの間に挟む文字列と末尾に入れる文字列を指定できる

print(1, "abc", True, None, [1], {2, 3}, {"a": "b"})
# 1 abc True None [1] {2, 3} {'a': 'b'}

print(1, "abc", True, None, [1], {2, 3}, {"a": "b"}, sep="|", end="END")
# 1|abc|True|None|[1]|{2, 3}|{'a': 'b'}END

出力先は標準出力以外にもできる

import sys
print("a", file=sys.stderr)
# a
# ↑ stderr に出力される

with open("output", "w") as f:
print("abc", file=f)

with open("output") as f:
print(f.read())
# abc

open

ファイルを開く
with を使うと close の手間を省ける

with open("/path/to/file") as f:
text = f.read()

f = open("/path/to/file", encoding="euc_jp", errors="ignore")
text = f.read()
f.close()

with open("/path/to/file", "w", newline="\n") as f:
f.write(text)

eval

文字列を Python の式として評価

eval("1 + 1")
# 2

式なので文はエラー

eval("a = 1")
# SyntaxError

a = 100
eval("a + 1")
# 101

評価するスコープのローカル変数とグローバル変数を設定できる
eval 文字列内でしか参照できない

eval("a + b", None, {"a": 1, "b": 2})
# 3
b
# NameError

locals を指定しなければ eval を実行するスコープのローカル変数を参照できるけど指定すると参照できなくなる

a = 100
def f():
a = 10
print(eval("a + 1"))
print(eval("a + 1", None, {}))
try:
print(eval("a + 1", {}, {}))
except:
print("error")
f()

# 11
# 101
# error

exec

文字列を Python のコードとして実行
eval と同じように globals と locals の設定ができる

exec("a = 10")
a
# 10
exec("10")
# None

a = 5
exec("print(a + b)", None, {"b": 10})
# 15

compile

Python コードをコンパイル
eval か exec 関数に渡して実行できる

code = compile("x = 0\nfor i in range(10): x += i", "filaname", "exec")
code
# <code object <module> at 0x0068F430, file "filaname", line 1>
exec(code)
x
# 45

code = compile("1 + 2", "filename", "eval")
eval(code)
# 3

値を返す式を eval しても mode が exec だと返り値がない

code = compile("1 + 2", "filename", "exec")
eval(code)
# None

mode が eval で文を compile しようとすると compile 時点でエラー
2 つめの引数のファイル名はエラーメッセージで使われる

compile("a = 1", "abcd123", "eval")
# Traceback (most recent call last):
# File "1.py", line 1, in <module>
# compile("a = 1", "abcd123", "eval")
# File "abcd123", line 1
# a = 1
# ^
# SyntaxError: invalid syntax

__import__

モジュールの import
import 文か importlib.import_module を使うほうが良い

os = __import__("os", globals(), locals(), [], 0)
os.name
# 'posix'

数字から始まったり記号を含むファイルでもインポートできる

echo "name='123-456'" > 123-456.py
echo "name='ぱいそん'" > ぱいそん.py
m = __import__("123-456", globals(), locals(), [], 0)
m.name
# '123-456'

n = __import__("ぱいそん", globals(), locals(), [], 0)
n.name
# 'ぱいそん'

exit

プログラムの終了

C:\tmpcodes\py>py
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\tmpcodes\py>

quit

参照が違うだけで 同じようにインスタンスが作られているので exit と一緒