Python の組み込み関数 repr の使い方です。
repr 関数で、オブジェクトの文字列表現を取得するコード例と、実行結果を載せました。
これらの実行結果も、repr 関数を使用して生成したものです。
具体的には、eval 関数でコードを実行して、その戻り値を repr 関数に渡して、記事に使いました。
それに加えて、『コード』と『実行結果の repr』を doctest にかけて、コード例にミスがないかを見ています。
自分の repr 関数の使い道です。
- doctest を実行するためのテキストを生成する。
- コマンドプロンプトと同じ表示を取得する。
repr 関数は、『Python プログラムの自動テスト』とか、『Python コード例の生成』といった用途で、使う場面がたくさんありました。
str を渡した結果
repr 関数に、str(文字列)を渡した結果です。
repr('') # '' 空文字列
"''"
普通の ASCII 文字列を渡した結果。
repr('12345') # '12345'
"'12345'"
repr('abcde') # 'abcde'
"'abcde'"
非 ASCII 文字列を渡した結果。
repr('ãäëÿ') # 'ãäëÿ'
"'ãäëÿ'"
repr('あ') # 'あ'
"'あ'"
repr('漢字') # '漢字'
"'漢字'"
repr('1aãあ漢字') # '1aãあ漢字'
"'1aãあ漢字'"
(参考)ascii 関数の場合です。
ascii('1aãあ漢字') # '1aãあ漢字'
"'1a\\xe3\\u3042\\u6f22\\u5b57'"
(参考)str 関数の場合です。
str('1aãあ漢字') # '1aãあ漢字'
'1aãあ漢字'
pathlib.Path を渡した結果
repr 関数に、pathlib の Path を渡した結果です。
(Python) class pathlib.Path(*pathsegments)
from pathlib import Path
repr(Path(r'F://abc/あいう/memo.txt')) # WindowsPath('F:/abc/あいう/memo.txt')
"WindowsPath('F:/abc/あいう/memo.txt')"
tuple を渡した結果
repr 関数に、tuple を渡した結果です。
repr(()) # () 空のタプル
'()'
repr((1, 'a', 'ã', 'あ')) # (1, 'a', 'ã', 'あ')
"(1, 'a', 'ã', 'あ')"
list を渡した結果
repr 関数に、list を渡した結果です。
(Python) class list([iterable])
repr([]) # [] 空のリスト
'[]'
repr([1, 'a', 'ã', 'あ']) # [1, 'a', 'ã', 'あ']
"[1, 'a', 'ã', 'あ']"
set を渡した結果
repr 関数に、集合の set を渡した結果です。
(Python) class set([iterable])
repr(set()) # set() 空の集合
'set()'
repr({1, 'a', 'ã', 'あ'}) # {'a', 1, 'ã', 'あ'}
"{'a', 1, 'ã', 'あ'}"
dict を渡した結果
repr 関数に、辞書の dict を渡した結果です。
repr({}) # {} 空の辞書
'{}'
repr({1: 'a', 2: 'ã', 3: 'あ'}) # {1: 'a', 2: 'ã', 3: 'あ'}
"{1: 'a', 2: 'ã', 3: 'あ'}"
repr({'あ': 'ã'}.keys()) # dict_keys(['あ'])
"dict_keys(['あ'])"
repr({'あ': 'ã'}.values()) # dict_values(['ã'])
"dict_values(['ã'])"
repr({'あ': 'ã'}.items()) # dict_items([('あ', 'ã')])
"dict_items([('あ', 'ã')])"
bytes を渡した結果
repr 関数に、bytes を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
repr(b'') # b'' 空のバイト列
"b''"
repr(b'\x00') # b'\x00'
"b'\\x00'"
repr(b'\x00\x01') # b'\x00\x01'
"b'\\x00\\x01'"
bytearray を渡した結果
repr 関数に、bytearray を渡した結果です。
(Python) class bytearray([source[, encoding[, errors]]])
repr(bytearray()) # bytearray(b'')
"bytearray(b'')"
repr(bytearray((0,))) # bytearray(b'\x00')
"bytearray(b'\\x00')"
repr(bytearray((0, 1))) # bytearray(b'\x00\x01')
"bytearray(b'\\x00\\x01')"
function を渡した結果
repr 関数に、function(関数)を渡した結果です。
repr(lambda x:x) # <function <lambda> at 0x0000000000000000>
'<function <lambda> at 0x0000000000000000>'
組み込み定数を渡した結果
repr 関数に、組み込み定数を渡した結果です。
repr(False) # False
'False'
repr(True) # True
'True'
repr(None) # None
'None'
int を渡した結果
repr 関数に、int(整数)を渡した結果です。
repr(1) # 1
'1'
repr(-1) # -1
'-1'
repr(0) # 0
'0'
float を渡した結果
repr 関数に、float(浮動小数点数)を渡した結果です。
repr(float('nan')) # nan
'nan'
repr(float('inf')) # inf
'inf'
repr(-0.1) # -0.1
'-0.1'
repr(0.0) # 0.0
'0.0'
repr(-0.0) # -0.0
'-0.0'
complex を渡した結果
repr 関数に、complex(複素数)を渡した結果です。
(Python) class complex([real[, imag]])
repr(complex(+3.0, +4.0)) # (3+4j)
'(3+4j)'
repr(complex(+0.0, +0.0)) # 0j
'0j'
repr(complex(-0.0, -0.0)) # (-0-0j)
'(-0-0j)'
repr(complex(float('-inf'), 4.0)) # (-inf+4j)
'(-inf+4j)'
repr(complex(float('nan'), 4.0)) # (nan+4j)
'(nan+4j)'
Decimal を渡した結果
repr 関数に、Decimal 型(十進数型)を渡した結果です。
(Python) class decimal.Decimal(value="0", context=None)
from decimal import Decimal
repr(Decimal(2)) # Decimal('2')
"Decimal('2')"
from decimal import Decimal
repr(Decimal(0.0)) # Decimal('0')
"Decimal('0')"
from decimal import Decimal
repr(Decimal(-0.0)) # Decimal('-0')
"Decimal('-0')"
from decimal import Decimal
repr(Decimal(-0.1)) # Decimal('-0.1000000000000000055511151231257827021181583404541015625')
"Decimal('-0.1000000000000000055511151231257827021181583404541015625')"
from decimal import Decimal
repr(Decimal('-inf')) # Decimal('-Infinity')
"Decimal('-Infinity')"
from decimal import Decimal
repr(Decimal('nan')) # Decimal('NaN')
"Decimal('NaN')"
datetime.datetime を渡した結果
repr 関数に、datetime.datetime を渡した結果です。
import datetime
repr(datetime.datetime.max) # datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
'datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)'
datetime.timedelta を渡した結果
repr 関数に、datetime.timedelta を渡した結果です。
import datetime
repr(datetime.timedelta(0)) # datetime.timedelta(0)
'datetime.timedelta(0)'
import datetime
repr(datetime.timedelta.max) # datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)
'datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)'
以上です。