久しぶりのPythonネタ

  • TureをFalseにする方法
>>> setattr(__builtins__, 'True', False)
>>> True
False

もちろん、

>>> True = False
>>> True
False

でも良いのだが、これだとカレントのモジュールにしか有効でないと思う。最初の例なら全てのモジュールで効いてくれると思うのだが、まだ未確認。
ちなみに、

>>> getattr(__builtins__, 'True') = False
  File "<stdin>", line 1
SyntaxError: can't assign to function call

ではダメだった。

>>> class Foo:pass
...
>>> f = Foo()
>>> f.y = 1
>>> f.y
1
>>> x = {}
>>> x.y = 1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'y'

何でだろう?じっくり考えるつもり。