暗黙bool値変換
この記事は Python Tips Advent Calendar 2012 4日目の記事です。
Python はいろんな値を、暗黙に bool 値として扱います。
False として扱われるデータは以下の通りです。
>>> false = False >>> none = None >>> int_zero = 0 >>> long_zero = 0L >>> float_zero = 0.0 >>> complex_zero = 0 + 0j >>> empty_tuple = () >>> empty_list = [] >>> empty_dict = {} >>> empty_set = set() >>> empty_string = '' >>> assert not int_zero >>> assert not long_zero >>> assert not float_zero >>> assert not complex_zero >>> assert not false >>> assert not none >>> assert not empty_tuple >>> assert not empty_list >>> assert not empty_dict >>> assert not empty_set >>> assert not empty_string
更に、ユーザ定義のクラスであっても、__nonzero__ で False を返すか、__len__ で 0 を返した場合も False として扱われます。(__nonzero__ の方が優先される)
>>> class UserDefined1(object): ... def __nonzero__(self): return False >>> ud1 = UserDefined1() >>> class UserDefined2(object): ... def __len__(self): return 0 >>> ud2 = UserDefined2() >>> assert not ud1 >>> assert not ud2
特に1つの if 文で複数の型を判定する可能性があるようなケースでは注意しましょう。
.