Python Gotcha's?
Tim Chase
python.list at tim.thechases.com
Wed Apr 4 19:42:56 EDT 2012
On 04/04/12 17:34, 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).
1) While I believe it was fixed in more recent releases (perhaps
Py3 or later, most of my code is still in 2.x), leaking of
list-comprehension variables into the surrounding scope has stung
me on occasion:
val = something_important
whatever = [val for val in iterable if condition(val)]
assert val == something_important, "ug!"
2) While totally understandable, the significance of leading
whitespace in docstrings/triple-quoted items occasionally catches
me in places I didn't intentionally want it:
class Foo:
def frobniculate(self, x, y):
"""Frobniculate the x & y
x is the macrowobble variance
y is the miniwibble grobulation
"""
pass
(there's now leading whitespace on lines 2 & 3, and an extra
trailing line of pure whitespace).
3) the peculiarities of old-style classes and new-style classes
in 2.x (mooted by 3.x) take careful reading of the docs if you're
overriding __getattr__ or __getattribute__, as well as possible
other old-vs-new gotchas.
4) the __del__ method may have things in the containing scopes
(such as modules imported at the top of the containing module)
that get garbage-collected before the __del__ is called. In
general, __del__ stinks, and is better replaced by "with"
statements using context managers.
5) the masking of system modules. On multiple occasions I've
created a local module named "email.py", and then upon importing
something else (I think it may have been smtplib...not sure), it
failed with a confusing error because the imported module found
mine rather than the system module.
Those are my off-the-top-of-the-head gotchas.
-tkc
More information about the Python-list
mailing list