Skip to content

Instantly share code, notes, and snippets.

@chobits
chobits / excepthook.py
Created April 12, 2012 07:33
python: hook exception handler
import sys
def my_excepthook(exc_type, exc_value, tb):
print 'My Excepthook:'
# traceback display: see tb_printinternal from cpython source
print ' Traceback (most recent call last):'
while tb:
filename = tb.tb_frame.f_code.co_filename
name = tb.tb_frame.f_code.co_name
@chobits
chobits / finalizer_garbage.py
Created April 5, 2012 12:32
Python: how to create finalizer garbage
import gc
class A():
# For Python, finalizers means instance objects with __del__ methods.
def __del__(self):
pass
print gc.garbage
# []
@chobits
chobits / gist:2205352
Created March 26, 2012 14:11
python: careful of swaping value
>>> class A():
... val = 0
...
>>> a = A()
>>> a.val, a = 1, a.val # right
>>> a = A()
>>> a, a.val = a.val, 1 # wrong
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'val'
@chobits
chobits / gist:2069014
Created March 18, 2012 04:57
python *args, **kwargs
>>> def test(a, b):
... print a, b
...
>>> test('hello', 'world')
hello world
>>> test(*('hello', 'world')) # tuple
hello world
>>> test(*iter(['hello', 'world'])) # iter
hello world
>>> test(*['hello', 'world']) # list
@chobits
chobits / gist:1976145
Created March 5, 2012 02:41
basic vim regex
numbers:
:%s/[0-9]\+/<something>/gc
strings:
:%s/[a-zA-Z]\+/<something>/gc
parentheses:
:%s/[\[\]{}()<>]\+/<something>/gc
special characters: