型を取得し、表示する
型を確認したいオブジェクトをtype()関数に渡すと、型オブジェクトを返します。 print関数などに型オブジェクトを渡すと、型の確認が可能です。type()関数の使い方
結果(型オブジェクト) = type(確認したいオブジェクト)
次のサンプルコードは整数、文字列、リストの型を表示します。
# 結果 = <class 'int'>
print(type(1))
# 結果 = <class 'str'>
print(type('test'))
# 結果 = <class 'list'>
print(type([]))

次のサンプルコードはdatetime型のインスタンスを生成し、型を確認しています。
import datetime
# datetime型のインスタンスを生成
datetimeValue = datetime.datetime.now()
# 変数 datetimeValue の型を取得
typeValue = type(datetimeValue)
# 結果 = dateValueの型は<class 'datetime.datetime'>です
print(f'datetimeValueの型は{typeValue}です。')
型を判定する
type()関数 が返す 型オブジェクト は is 演算子を使用し、型が一致するか確認可能です。if type(確認したいオブジェクト) is 型:
型が一致したときの処理
次のコードは type関数と is 演算子を使用し、型の判定をしています。
import datetime
# datetime型のインスタンスを生成
datetimeValue = datetime.datetime.now()
# 変数 datetimeValue の型を確認
if type(datetimeValue) is str:
print(f'string型です。')
elif type(datetimeValue) is datetime.datetime:
print(f'datetime型です。')
次のコードはPython組み込み型の判定をしています。
value = 'test'
# 変数 value の型を判定
if type(value) is bool:
print('bool型(真理値)です。')
elif type(value) is int:
print('int型(整数)です。')
elif type(value) is float:
print('float型(浮動小数点数)です。')
elif type(value) is complex:
print('complex型(複素数)です。')
elif type(value) is list:
print('list型(配列)です。')
elif type(value) is tuple:
print('tuple型(タプル)です。')
elif type(value) is range:
print('range型(範囲)です。')
elif type(value) is str:
print('str型(文字列/テキストシーケンス型)です。')
elif type(value) is bytes:
print('bytes型(バイト列/バイナリシーケンス型)です。')
elif type(value) is bytearray:
print('bytearray型(可変なbytes)です。')
elif type(value) is memoryview:
print('memoryview型(メモリビュー)です。')
elif type(value) is set:
print('set型(集合型)です。')
elif type(value) is frozenset:
print('frozenset型(集合型)です。')
elif type(value) is dict:
print('dict型(マッピング型/辞書)です。')
else:
print(f'{type(value)}型です。')
参考資料
検証環境
- Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 21H2 OS Build 19044.2130 Experience: Windows Feature Experience Pack 120.2212.4180.0