reversed("andelf")== "fledna"

andelf fledna Feather

2011年6月13日星期一

How to make your source code compatiable with py2.4 to py3.2

* suggestion

put all compat fix code into a compat.py, import it.

* imports fix

some modules have been moved or rearanged.

* unicode fix

use from __future__ import unicode_literals, it only supports py2.6+
fix `unicode`, `basestring` in py3+

* grammer

with expression: never use. if you want to support py2.5-

except ... as ...: use function fix

* sample compat.py

try:
____import urlparse
____from urllib import urlencode, quote, unquote, splithost, splittype
____urlparse.urlencode = urlencode
____urlparse.quote = quote
____urlparse.unquote = unquote
____urlparse.splithost = splithost
____urlparse.splittype = splittype
____# fix py2.5-
____if not hasattr(urlparse, 'parse_qs'):
________from cgi import parse_qs
________urlparse.parse_qs = parse_qs
____globals()['bytes'] = str
except ImportError:
____import urllib.parse as urlparse
____globals()['unicode'] = str
____globals()['basestring'] = str

2011年6月10日星期五

实现 python 源码兼容 python2.4 -> python3.2 的兼容

def except_as():
____return sys.exc_info()[1]

这样就可以搞定不支持 except ... as ... 的情况了.

2011年6月8日星期三

百度贴吧如何贴代码?

浏览器地址栏执行
javascript:document.getElementById('bdeTextArea').setAttribute('onpaste', null);

2011年6月5日星期日

使用 class ClassName: 如何创建 new-style class

class A:
__metaclass__ = type
pass

答案是使用 __metaclass__

2011年6月3日星期五

如何获取文件大小?

除了 stat...如果对于已经有fp的话...可以

with open(filename, 'rb') as fp:
fp.seek(0, 2)
filesize = fp.tell()

2011年5月24日星期二

why a STORE_FAST after INPLACE_ADD

python 2.7


In [20]: def foo():
....: a += 1
....:

In [21]: dis.dis(foo)
2 0 LOAD_FAST 0 (a)
3 LOAD_CONST 1 (1)
6 INPLACE_ADD
7 STORE_FAST 0 (a)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE3

some notes on python sets

according to the doc, we have a set and frozenset built-in func in
python now.

so what's frozenset?

doc says:
Set and ImmutableSet were renamed to set and frozenset.

they don't act like str and unicode, where there's a basestring! no
baseset!!

so you must use isinstance(x, (set, frozenset)).
check it with set.mro().

PS: I got a new handful type/function:
function = type(lambda : None)
Docstring:
function(code, globals[, name[, argdefs[, closure]]])

Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.