-
添加
collections.Counter
class to support convenient counting of unique items in a sequence or iterable:
>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter({'blue': 3, 'red': 2, 'green': 1})
(Contributed by Raymond Hettinger;
bpo-1696199
)。
-
Added a new module,
tkinter.ttk
for access to the Tk themed widget set. The basic idea of ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.
(Contributed by Guilherme Polo;
bpo-2983
)。
-
The
gzip.GzipFile
and
bz2.BZ2File
classes now support the context management protocol:
>>> # Automatically close file after writing
>>> with gzip.GzipFile(filename, "wb") as f:
... f.write(b"xxx")
(Contributed by Antoine Pitrou.)
-
The
decimal
module now supports methods for creating a decimal object from a binary
float
. The conversion is exact but can sometimes be surprising:
>>> Decimal.from_float(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
The long decimal result shows the actual binary fraction being stored for
1.1
. The fraction has many digits because
1.1
cannot be exactly represented in binary.
(Contributed by Raymond Hettinger and Mark Dickinson.)
-
The
itertools
module grew two new functions. The
itertools.combinations_with_replacement()
function is one of four for generating combinatorics including permutations and Cartesian products. The
itertools.compress()
function mimics its namesake from APL. Also, the existing
itertools.count()
function now has an optional
step
argument and can accept any type of counting sequence including
fractions.Fraction
and
decimal.Decimal
:
>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']
>>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]
>>> c = count(start=Fraction(1,2), step=Fraction(1,6))
>>> [next(c), next(c), next(c), next(c)]
[Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]
(Contributed by Raymond Hettinger.)
-
collections.namedtuple()
now supports a keyword argument
rename
which lets invalid fieldnames be automatically converted to positional names in the form _0, _1, etc. This is useful when the field names are being created by an external source such as a CSV header, SQL field list, or user input:
>>> query = input()
SELECT region, dept, count(*) FROM main GROUPBY region, dept
>>> cursor.execute(query)
>>> query_fields = [desc[0] for desc in cursor.description]
>>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)
>>> pprint.pprint([UserQuery(*row) for row in cursor])
[UserQuery(region='South', dept='Shipping', _2=185),
UserQuery(region='North', dept='Accounting', _2=37),
UserQuery(region='West', dept='Sales', _2=419)]
(Contributed by Raymond Hettinger;
bpo-1818
)。
-
The
re.sub()
,
re.subn()
and
re.split()
functions now accept a flags parameter.
(Contributed by Gregory Smith.)
-
The
logging
module now implements a simple
logging.NullHandler
class for applications that are not using logging but are calling library code that does. Setting-up a null handler will suppress spurious warnings such as “No handlers could be found for logger foo”:
>>> h = logging.NullHandler()
>>> logging.getLogger("foo").addHandler(h)
(Contributed by Vinay Sajip;
bpo-4384
).
-
The
runpy
module which supports the
-m
command line switch now supports the execution of packages by looking for and executing a
__main__
submodule when a package name is supplied.
(Contributed by Andi Vajda;
bpo-4195
)。
-
The
pdb
module can now access and display source code loaded via
zipimport
(or any other conformant
PEP 302
loader).
(Contributed by Alexander Belopolsky;
bpo-4201
)。
-
functools.partial
objects can now be pickled.
-
添加
pydoc
help topics for symbols so that
help('@')
works as expected in the interactive environment.
(Contributed by David Laban;
bpo-4739
)。
-
The
unittest
module now supports skipping individual tests or classes of tests. And it supports marking a test as an expected failure, a test that is known to be broken, but shouldn’t be counted as a failure on a TestResult:
class TestGizmo(unittest.TestCase):
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
def test_gizmo_on_windows(self):
...
@unittest.expectedFailure
def test_gimzo_without_required_library(self):
...
Also, tests for exceptions have been builtout to work with context managers using the
with
语句:
def test_division_by_zero(self):
with self.assertRaises(ZeroDivisionError):
x / 0
In addition, several new assertion methods were added including
assertSetEqual()
,
assertDictEqual()
,
assertDictContainsSubset()
,
assertListEqual()
,
assertTupleEqual()
,
assertSequenceEqual()
,
assertRaisesRegexp()
,
assertIsNone()
,和
assertIsNotNone()
.
(Contributed by Benjamin Peterson and Antoine Pitrou.)
-
The
io
module has three new constants for the
seek()
方法:
SEEK_SET
,
SEEK_CUR
,和
SEEK_END
.
-
The
sys.version_info
tuple is now a named tuple:
>>> sys.version_info
sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)
(Contributed by Ross Light;
bpo-4285
)。
-
The
nntplib
and
imaplib
modules now support IPv6.
(Contributed by Derek Morr;
bpo-1655
and
bpo-1664
)。
-
The
pickle
module has been adapted for better interoperability with Python 2.x when used with protocol 2 or lower. The reorganization of the standard library changed the formal reference for many objects. For example,
__builtin__.set
in Python 2 is called
builtins.set
in Python 3. This change confounded efforts to share data between different versions of Python. But now when protocol 2 or lower is selected, the pickler will automatically use the old Python 2 names for both loading and dumping. This remapping is turned-on by default but can be disabled with the
fix_imports
选项:
>>> s = {1, 2, 3}
>>> pickle.dumps(s, protocol=0)
b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
>>> pickle.dumps(s, protocol=0, fix_imports=False)
b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
An unfortunate but unavoidable side-effect of this change is that protocol 2 pickles produced by Python 3.1 won’t be readable with Python 3.0. The latest pickle protocol, protocol 3, should be used when migrating data between Python 3.x implementations, as it doesn’t attempt to remain compatible with Python 2.x.
(Contributed by Alexandre Vassalotti and Antoine Pitrou,
bpo-6137
)。
-
新的模块,
importlib
was added. It provides a complete, portable, pure Python reference implementation of the
import
statement and its counterpart, the
__import__()
function. It represents a substantial step forward in documenting and defining the actions that take place during imports.
(Contributed by Brett Cannon.)