Python Gotcha's?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Apr 4 19:07:51 EDT 2012
On Wed, 04 Apr 2012 15:34:20 -0700, Miki Tebeka wrote:
> Greetings,
>
> I'm going to give a "Python Gotcha's" talk at work. If you have an
> interesting/common "Gotcha" (warts/dark corners ...) please share.
>
> (Note that I want over http://wiki.python.org/moin/PythonWarts already).
The GIL prevents Python from taking advantage of multiple cores in your
CPU when using multiple threads.
Solution: use a GIL-less Python, like IronPython or Jython, or use
multiple processes instead of threads.
exec() and execfile() are unintuitive if you supply separate dicts for
the globals and locals arguments.
http://bugs.python.org/issue1167300
http://bugs.python.org/issue14049
Note that both of these are flagged as WON'T FIX.
Solution: to emulate top-level code, pass the same dict as globals and
locals.
max() and min() fail with a single argument:
max(2, 3) => 3
max(3) => raises exception
Solution: don't do that. Or pass a list:
max([2, 3]) => 3
max([3]) => 3
Splitting on None and splitting on space is not identical:
"".split() => []
"".split(' ') => ['']
JSON expects double-quote marks, not single:
v = json.loads("{'test':'test'}") fails
v = json.loads('{"test":"test"}') succeeds
If you decorate a function, by default the docstring is lost.
@decorate
def spam(x, y):
"""blah blah blah blah"""
spam.__doc__ => raises exception
Solution: make sure your decorator uses functools.wraps().
--
Steven
More information about the Python-list
mailing list