When specifying an exception variable, always use as
instead of a comma (e.g. except Exception as e
or except (TypeError, IOError) as e
). Use e.args
to access the error arguments (instead of iterating over or subscripting e
).
Use in
(not has_key()
) to determine if a dictionary has a particular key.
Always use the I/O functions from the io
module rather than the native I/O functions (e.g. io.open()
rather than open()
).
When opening a file, always use the t
(text) or b
(binary) mode flag.
When creating classes, always specify a parent class to ensure that it is a "new-style" class (e.g. class Foo(object):
rather than class Foo:
)
Be aware of the bytes type added in Python 3. Many places where strings are used in Python 2 use bytes or bytearrays in Python 3 (for example, the pipes used with subprocess.Popen()
). Code should handle both possibilities.
Be aware that the items()
, keys()
, and values()
methods of dictionaries return lists in Python 2 and views in Python 3. In many case, no special handling is required, but if the code needs to use list methods on the result, cast the result to list first.
Do not raise or catch strings as exceptions (e.g. raise "Bad thing"
).
Do not use the cmp
parameter of sorting functions (use key
instead, if needed) or the __cmp__()
method of classes (implement rich comparison methods such as __lt__()
instead, if needed).
Do not use the buffer
type.
Do not use features not available in all targeted Python versions. Common examples include:
The html
, ipaddress
, and UserDict
modules
The subprocess.run()
function
The subprocess.DEVNULL
constant
subprocess
module-specific exceptions