We still have 27 failing tests (down from 39).
>>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
- >>> print(C.output(header="Cookie:"))
+ >>> print((C.output(header="Cookie:")))
Cookie: rocky=road; Path=/cookie
- >>> print(C.output(attrs=[], header="Cookie:"))
+ >>> print((C.output(attrs=[], header="Cookie:")))
Cookie: rocky=road
The load() method of a Cookie extracts cookies from a string. In a
>>> C = Cookie.SmartCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
- >>> print(C)
+ >>> print((C))
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Each element of the Cookie also supports all of the RFC 2109
>>> C = Cookie.SmartCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
- >>> print(C)
+ >>> print((C))
Set-Cookie: oreo=doublestuff; Path=/
Each dictionary element has a 'value' attribute, which gives you
fact, this simply returns a SmartCookie.
>>> C = Cookie.Cookie()
- >>> print(C.__class__.__name__)
+ >>> print((C.__class__.__name__))
SmartCookie
>>> from ctypes import *
>>> array = (c_char_p * 5)()
->>> print array._objects
+>>> print(array._objects)
None
>>>
... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)]
...
>>> x = X()
->>> print x._objects
+>>> print(x._objects)
None
>>>
The'array' attribute of the 'x' object shares part of the memory buffer
of 'x' ('_b_base_' is either None, or the root object owning the memory block):
->>> print x.array._b_base_ # doctest: +ELLIPSIS
+>>> print(x.array._b_base_) # doctest: +ELLIPSIS
<ctypes.test.test_objects.X object at 0x...>
>>>
>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
Decimal("-2.20")
>>> dig = Decimal(1)
->>> print dig / Decimal(3)
+>>> print(dig / Decimal(3))
0.333333333
>>> getcontext().prec = 18
->>> print dig / Decimal(3)
+>>> print(dig / Decimal(3))
0.333333333333333333
->>> print dig.sqrt()
+>>> print(dig.sqrt())
1
->>> print Decimal(3).sqrt()
+>>> print(Decimal(3).sqrt())
1.73205080756887729
->>> print Decimal(3) ** 123
+>>> print(Decimal(3) ** 123)
4.85192780976896427E+58
>>> inf = Decimal(1) / Decimal(0)
->>> print inf
+>>> print(inf)
Infinity
>>> neginf = Decimal(-1) / Decimal(0)
->>> print neginf
+>>> print(neginf)
-Infinity
->>> print neginf + inf
+>>> print(neginf + inf)
NaN
->>> print neginf * inf
+>>> print(neginf * inf)
-Infinity
->>> print dig / 0
+>>> print(dig / 0)
Infinity
>>> getcontext().traps[DivisionByZero] = 1
->>> print dig / 0
+>>> print(dig / 0)
Traceback (most recent call last):
...
...
decimal.DivisionByZero: x / 0
>>> c = Context()
>>> c.traps[InvalidOperation] = 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
0
>>> c.divide(Decimal(0), Decimal(0))
Decimal("NaN")
>>> c.traps[InvalidOperation] = 1
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>> c.flags[InvalidOperation] = 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
0
->>> print c.divide(Decimal(0), Decimal(0))
+>>> print(c.divide(Decimal(0), Decimal(0)))
Traceback (most recent call last):
...
...
...
decimal.InvalidOperation: 0 / 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>> c.flags[InvalidOperation] = 0
>>> c.traps[InvalidOperation] = 0
->>> print c.divide(Decimal(0), Decimal(0))
+>>> print(c.divide(Decimal(0), Decimal(0)))
NaN
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>>
"""
# as the doctest module doesn't understand __future__ statements
"""
>>> from __future__ import with_statement
- >>> print getcontext().prec
+ >>> print(getcontext().prec)
28
>>> with localcontext():
... ctx = getcontext()
... ctx.prec() += 2
- ... print ctx.prec
- ...
+ ... print(ctx.prec)
+ ...
30
>>> with localcontext(ExtendedContext):
- ... print getcontext().prec
- ...
+ ... print(getcontext().prec)
+ ...
9
- >>> print getcontext().prec
+ >>> print(getcontext().prec)
28
"""
if ctx is None: ctx = getcontext()
sequences. As a rule of thumb, a .ratio() value over 0.6 means the
sequences are close matches:
- >>> print(round(s.ratio(), 3))
+ >>> print((round(s.ratio(), 3)))
0.866
>>>
.get_matching_blocks() is handy:
>>> for block in s.get_matching_blocks():
- ... print("a[%d] and b[%d] match for %d elements" % block)
+ ... print(("a[%d] and b[%d] match for %d elements" % block))
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
use .get_opcodes():
>>> for opcode in s.get_opcodes():
- ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
+ ... print(("%6s a[%d:%d] b[%d:%d]" % opcode))
equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
equal a[8:29] b[17:38]
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
- ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
- ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
+ ... print((("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
+ ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))))
delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y)
>>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
... ' ^ ^ ^ ', '+ ^ ^ ^ ')
- >>> for line in results: print(repr(line))
- ...
+ >>> for line in results: print((repr(line)))
+ ...
'- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n'
'+ \t\tabcdefGhijkl\n'
... 'zero one tree four'.split(), 'Original', 'Current',
... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
... lineterm=''):
- ... print(line)
+ ... print((line))
--- Original Sat Jan 26 23:30:50 1991
+++ Current Fri Jun 06 10:20:52 2003
@@ -1,4 +1,4 @@
The str() of a `VersionPredicate` provides a normalized
human-readable version of the expression::
- >>> print v
+ >>> print(v)
pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
The `satisfied_by()` method can be used to determine with a given
>>> runner = DocTestRunner(verbose=False)
>>> tests.sort(key = lambda test: test.name)
>>> for test in tests:
- ... print test.name, '->', runner.run(test)
+ ... print(test.name, '->', runner.run(test))
_TestClass -> (0, 2)
_TestClass.__init__ -> (0, 2)
_TestClass.get -> (0, 2)
... Ho hum
... '''
- >>> print script_from_examples(text)
+ >>> print(script_from_examples(text))
# Here are examples of simple math.
#
# Python has super accurate integer addition
"""val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
- >>> print t.get()
+ >>> print(t.get())
123
"""
"""get() -> return TestClass's associated value.
>>> x = _TestClass(-42)
- >>> print x.get()
+ >>> print(x.get())
-42
"""
"blank lines": r"""
Blank lines can be marked with <BLANKLINE>:
- >>> print 'foo\n\nbar\n'
+ >>> print('foo\n\nbar\n')
foo
<BLANKLINE>
bar
"ellipsis": r"""
If the ellipsis flag is used, then '...' can be used to
elide substrings in the desired output:
- >>> print range(1000) #doctest: +ELLIPSIS
+ >>> print(range(1000)) #doctest: +ELLIPSIS
[0, 1, 2, ..., 999]
""",
"whitespace normalization": r"""
If the whitespace normalization flag is used, then
differences in whitespace are ignored.
- >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
+ >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29]
>>> from nntplib import NNTP
>>> s = NNTP('news')
>>> resp, count, first, last, name = s.group('comp.lang.python')
->>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
+>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group comp.lang.python has 51 articles, range 5770 to 5821
>>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> resp = s.quit()
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
- >>> print s.help()
+ >>> print(s.help())
This is Sendmail version 8.8.4
Topics:
HELO EHLO MAIL RCPT DATA
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n')
->>> print tn.read_all()
+>>> print(tn.read_all())
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
def f(self):
'''
- >>> print TwoNames().f()
+ >>> print(TwoNames().f())
f
'''
return 'f'
def w_blank():
"""
>>> if 1:
- ... print 'a'
- ... print
- ... print 'b'
+ ... print('a')
+ ... print()
+ ... print('b')
a
<BLANKLINE>
b
consts: ('None',)
>>> def attrs(obj):
-... print obj.attr1
-... print obj.attr2
-... print obj.attr3
+... print(obj.attr1)
+... print(obj.attr2)
+... print(obj.attr3)
>>> dump(attrs.func_code)
name: attrs
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
-... print elem.upper()
+... print(elem.upper())
G
H
I
...
>>> for value in roundrobin('abc', 'd', 'efgh'):
-... print value
-...
+... print(value)
+...
a
d
e
... d.append(pair)
... return list(d)
...
->>> print maketree('abcdefgh')
+>>> print(maketree('abcdefgh'))
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
"""
Here's the new type at work:
- >>> print defaultdict # show our type
+ >>> print(defaultdict) # show our type
<class 'test.test_descrtut.defaultdict'>
- >>> print type(defaultdict) # its metatype
+ >>> print(type(defaultdict)) # its metatype
<type 'type'>
>>> a = defaultdict(default=0.0) # create an instance
- >>> print a # show the instance
+ >>> print(a) # show the instance
{}
- >>> print type(a) # show its type
+ >>> print(type(a)) # show its type
<class 'test.test_descrtut.defaultdict'>
- >>> print a.__class__ # show its class
+ >>> print(a.__class__) # show its class
<class 'test.test_descrtut.defaultdict'>
- >>> print type(a) is a.__class__ # its type is its class
+ >>> print(type(a) is a.__class__) # its type is its class
True
>>> a[1] = 3.25 # modify the instance
- >>> print a # show the new value
+ >>> print(a) # show the new value
{1: 3.25}
- >>> print a[1] # show the new item
+ >>> print(a[1]) # show the new item
3.25
- >>> print a[0] # a non-existant item
+ >>> print(a[0]) # a non-existant item
0.0
>>> a.merge({1:100, 2:200}) # use a dict method
- >>> print sortdict(a) # show the result
+ >>> print(sortdict(a)) # show the result
{1: 3.25, 2: 200}
>>>
dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval():
- >>> print sorted(a.keys())
+ >>> print(sorted(a.keys()))
[1, 2]
>>> exec("x = 3; print x", a)
3
- >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
+ >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x)))
[1, 2, '__builtins__', 'x']
- >>> print a['x']
+ >>> print(a['x'])
3
>>>
just like classic classes:
>>> a.default = -1
- >>> print a["noway"]
+ >>> print(a["noway"])
-1
>>> a.default = -1000
- >>> print a["noway"]
+ >>> print(a["noway"])
-1000
>>> 'default' in dir(a)
True
>>> a.x1 = 100
>>> a.x2 = 200
- >>> print a.x1
+ >>> print(a.x1)
100
>>> d = dir(a)
>>> 'default' in d and 'x1' in d and 'x2' in d
True
- >>> print sortdict(a.__dict__)
+ >>> print(sortdict(a.__dict__))
{'default': -1000, 'x1': 100, 'x2': 200}
>>>
"""
static methods in C++ or Java. Here's an example:
>>> class C:
- ...
+ ...
... @staticmethod
... def foo(x, y):
- ... print "staticmethod", x, y
+ ... print("staticmethod", x, y)
>>> C.foo(1, 2)
staticmethod 1 2
>>> class C:
... @classmethod
... def foo(cls, y):
- ... print "classmethod", cls, y
+ ... print("classmethod", cls, y)
>>> C.foo(1)
classmethod <class 'test.test_descrtut.C'> 1
>>> class E(C):
... @classmethod
... def foo(cls, y): # override C.foo
- ... print "E.foo() called"
+ ... print("E.foo() called")
... C.foo(y)
>>> E.foo(1)
>>> a = C()
>>> a.x = 10
- >>> print a.x
+ >>> print(a.x)
10
>>> a.x = -10
- >>> print a.x
+ >>> print(a.x)
0
>>>
>>> a = C()
>>> a.x = 10
- >>> print a.x
+ >>> print(a.x)
10
>>> a.x = -10
- >>> print a.x
+ >>> print(a.x)
0
>>>
"""
>>> class A: # implicit new-style class
... def save(self):
-... print "called A.save()"
+... print("called A.save()")
>>> class B(A):
... pass
>>> class C(A):
... def save(self):
-... print "called C.save()"
+... print("called C.save()")
>>> class D(B, C):
... pass
>>> class A(object): # explicit new-style class
... def save(self):
-... print "called A.save()"
+... print("called A.save()")
>>> class B(A):
... pass
>>> class C(A):
... def save(self):
-... print "called C.save()"
+... print("called C.save()")
>>> class D(B, C):
... pass
Cooperative methods and "super"
->>> print D().m() # "DCBA"
+>>> print(D().m()) # "DCBA"
DCBA
"""
>>> class A:
... def foo(self):
-... print "called A.foo()"
+... print("called A.foo()")
>>> class B(A):
... pass
"""
Blah blah
- >>> print sample_func(22)
+ >>> print(sample_func(22))
44
Yee ha!
class SampleClass:
"""
- >>> print 1
+ >>> print(1)
1
>>> # comments get ignored. so are empty PS1 and PS2 prompts:
>>> sc = SampleClass(3)
>>> for i in range(10):
... sc = sc.double()
- ... print sc.get(),
+ ... print(sc.get(), end=' ')
6 12 24 48 96 192 384 768 1536 3072
"""
def __init__(self, val):
"""
- >>> print SampleClass(12).get()
+ >>> print(SampleClass(12).get())
12
"""
self.val = val
def double(self):
"""
- >>> print SampleClass(12).double().get()
+ >>> print(SampleClass(12).double().get())
24
"""
return SampleClass(self.val + self.val)
def get(self):
"""
- >>> print SampleClass(-5).get()
+ >>> print(SampleClass(-5).get())
-5
"""
return self.val
def a_staticmethod(v):
"""
- >>> print SampleClass.a_staticmethod(10)
+ >>> print(SampleClass.a_staticmethod(10))
11
"""
return v+1
def a_classmethod(cls, v):
"""
- >>> print SampleClass.a_classmethod(10)
+ >>> print(SampleClass.a_classmethod(10))
12
- >>> print SampleClass(0).a_classmethod(10)
+ >>> print(SampleClass(0).a_classmethod(10))
12
"""
return v+2
a_classmethod = classmethod(a_classmethod)
a_property = property(get, doc="""
- >>> print SampleClass(22).a_property
+ >>> print(SampleClass(22).a_property)
22
""")
"""
>>> x = SampleClass.NestedClass(5)
>>> y = x.square()
- >>> print y.get()
+ >>> print(y.get())
25
"""
def __init__(self, val=0):
"""
- >>> print SampleClass.NestedClass().get()
+ >>> print(SampleClass.NestedClass().get())
0
"""
self.val = val
class SampleNewStyleClass(object):
r"""
- >>> print '1\n2\n3'
+ >>> print('1\n2\n3')
1
2
3
"""
def __init__(self, val):
"""
- >>> print SampleNewStyleClass(12).get()
+ >>> print(SampleNewStyleClass(12).get())
12
"""
self.val = val
def double(self):
"""
- >>> print SampleNewStyleClass(12).double().get()
+ >>> print(SampleNewStyleClass(12).double().get())
24
"""
return SampleNewStyleClass(self.val + self.val)
def get(self):
"""
- >>> print SampleNewStyleClass(-5).get()
+ >>> print(SampleNewStyleClass(-5).get())
-5
"""
return self.val
>>> parser = doctest.DocTestParser()
>>> test = parser.get_doctest(docstring, globs, 'some_test',
... 'some_file', 20)
- >>> print test
+ >>> print(test)
<DocTest some_test from some_file:20 (2 examples)>
>>> len(test.examples)
2
>>> tests = finder.find(sample_func)
- >>> print tests # doctest: +ELLIPSIS
+ >>> print(tests) # doctest: +ELLIPSIS
[<DocTest sample_func from ...:13 (1 example)>]
The exact name depends on how test_doctest was invoked, so allow for
>>> finder = doctest.DocTestFinder()
>>> tests = finder.find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
>>> tests = finder.find(SampleNewStyleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
1 SampleNewStyleClass
1 SampleNewStyleClass.__init__
1 SampleNewStyleClass.double
>>> import test.test_doctest
>>> tests = finder.find(m, module=test.test_doctest)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
1 some_module
3 some_module.SampleClass
3 some_module.SampleClass.NestedClass
>>> from test import doctest_aliases
>>> tests = excl_empty_finder.find(doctest_aliases)
- >>> print len(tests)
+ >>> print(len(tests))
2
- >>> print tests[0].name
+ >>> print(tests[0].name)
test.doctest_aliases.TwoNames
TwoNames.f and TwoNames.g are bound to the same object.
>>> tests = doctest.DocTestFinder().find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
>>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
>>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
Line numbers
>>> parser = doctest.DocTestParser()
>>> for piece in parser.parse(s):
... if isinstance(piece, doctest.Example):
- ... print 'Example:', (piece.source, piece.want, piece.lineno)
+ ... print('Example:', (piece.source, piece.want, piece.lineno))
... else:
- ... print ' Text:', repr(piece)
+ ... print(' Text:', repr(piece))
Text: '\n'
Example: ('x, y = 2, 3 # no output expected\n', '', 1)
Text: ''
The `get_examples` method returns just the examples:
>>> for piece in parser.get_examples(s):
- ... print (piece.source, piece.want, piece.lineno)
+ ... print((piece.source, piece.want, piece.lineno))
('x, y = 2, 3 # no output expected\n', '', 1)
('if 1:\n print x\n print y\n', '2\n3\n', 2)
('x+y\n', '5\n', 9)
>>> (test.name, test.filename, test.lineno)
('name', 'filename', 5)
>>> for piece in test.examples:
- ... print (piece.source, piece.want, piece.lineno)
+ ... print((piece.source, piece.want, piece.lineno))
('x, y = 2, 3 # no output expected\n', '', 1)
('if 1:\n print x\n print y\n', '2\n3\n', 2)
('x+y\n', '5\n', 9)
(0, 1)
An example from the docs:
- >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
+ >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
... also matches nothing:
>>> for i in range(100):
- ... print i**2, #doctest: +ELLIPSIS
+ ... print(i**2, end=' ') #doctest: +ELLIPSIS
0 1...4...9 16 ... 36 49 64 ... 9801
... can be surprising; e.g., this test passes:
>>> for i in range(21): #doctest: +ELLIPSIS
- ... print i,
+ ... print(i, end=' ')
0 1 2 ...1...2...0
Examples from the docs:
- >>> print range(20) # doctest:+ELLIPSIS
+ >>> print(range(20)) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]
- >>> print range(20) # doctest: +ELLIPSIS
+ >>> print(range(20)) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19]
UncheckedBlowUpError: Nobody checks me.
>>> import random
- >>> print random.random() # doctest: +SKIP
+ >>> print(random.random()) # doctest: +SKIP
0.721216923889
The REPORT_UDIFF flag causes failures that involve multi-line expected
>>> import test.test_doctest
>>> name = 'test.test_doctest.sample_func'
- >>> print doctest.testsource(test.test_doctest, name)
+ >>> print(doctest.testsource(test.test_doctest, name))
# Blah blah
#
print sample_func(22)
<BLANKLINE>
>>> name = 'test.test_doctest.SampleNewStyleClass'
- >>> print doctest.testsource(test.test_doctest, name)
+ >>> print(doctest.testsource(test.test_doctest, name))
print '1\n2\n3'
# Expected:
## 1
<BLANKLINE>
>>> name = 'test.test_doctest.SampleClass.a_classmethod'
- >>> print doctest.testsource(test.test_doctest, name)
+ >>> print(doctest.testsource(test.test_doctest, name))
print SampleClass.a_classmethod(10)
# Expected:
## 12
Trailing spaces in expected output are significant:
>>> x, y = 'foo', ''
- >>> print x, y
+ >>> print(x, y)
foo \n
"""
... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
>>> import unittest
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
Now, when we run the test:
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
Then the default eporting options are ignored:
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
u"""A module to test whether doctest recognizes some 2.2 features,
like static and class methods.
->>> print 'yup' # 1
+>>> print('yup') # 1
yup
We include some (random) encoded (utf-8) text in the text surrounding
class C(object):
u"""Class C.
- >>> print C() # 2
+ >>> print(C()) # 2
42
def __init__(self):
"""C.__init__.
- >>> print C() # 3
+ >>> print(C()) # 3
42
"""
def __str__(self):
"""
- >>> print C() # 4
+ >>> print(C()) # 4
42
"""
return "42"
class D(object):
"""A nested D class.
- >>> print "In D!" # 5
+ >>> print("In D!") # 5
In D!
"""
def nested(self):
"""
- >>> print 3 # 6
+ >>> print(3) # 6
3
"""
"""
>>> c = C() # 7
>>> c.x = 12 # 8
- >>> print c.x # 9
+ >>> print(c.x) # 9
-12
"""
return -self._x
"""
>>> c = C() # 10
>>> c.x = 12 # 11
- >>> print c.x # 12
+ >>> print(c.x) # 12
-12
"""
self._x = value
x = property(getx, setx, doc="""\
>>> c = C() # 13
>>> c.x = 12 # 14
- >>> print c.x # 15
+ >>> print(c.x) # 15
-12
""")
"""
A static method.
- >>> print C.statm() # 16
+ >>> print(C.statm()) # 16
666
- >>> print C().statm() # 17
+ >>> print(C().statm()) # 17
666
"""
return 666
"""
A class method.
- >>> print C.clsm(22) # 18
+ >>> print(C.clsm(22)) # 18
22
- >>> print C().clsm(23) # 19
+ >>> print(C().clsm(23)) # 19
23
"""
return val
... yield 2
>>> for i in f():
- ... print i
+ ... print(i)
1
2
>>> g = f()
... raise StopIteration
... except:
... yield 42
- >>> print list(g2())
+ >>> print(list(g2()))
[42]
This may be surprising at first:
>>> def creator():
... r = yrange(5)
- ... print "creator", r.next()
+ ... print("creator", r.next())
... return r
- ...
+ ...
>>> def caller():
... r = creator()
... for i in r:
- ... print "caller", i
- ...
+ ... print("caller", i)
+ ...
>>> caller()
creator 0
caller 1
... return
... except:
... yield 1
- >>> print list(f1())
+ >>> print(list(f1()))
[]
because, as in any function, return simply exits, but
... raise StopIteration
... except:
... yield 42
- >>> print list(f2())
+ >>> print(list(f2()))
[42]
because StopIteration is captured by a bare "except", as is any
... finally:
... yield 10
... yield 11
- >>> print list(f())
+ >>> print(list(f()))
[1, 2, 4, 5, 8, 9, 10, 11]
>>>
>>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> # Print the nodes of the tree in in-order.
>>> for x in t:
- ... print x,
+ ... print(x, end=' ')
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
>>> # A non-recursive generator.
>>> # Exercise the non-recursive generator.
>>> for x in t:
- ... print x,
+ ... print(x, end=' ')
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
"""
>>> seq = range(1, 5)
>>> for k in range(len(seq) + 2):
-... print "%d-combs of %s:" % (k, seq)
+... print("%d-combs of %s:" % (k, seq))
... for c in gcomb(seq, k):
-... print " ", c
+... print(" ", c)
0-combs of [1, 2, 3, 4]:
[]
1-combs of [1, 2, 3, 4]:
<type 'generator'>
>>> [s for s in dir(i) if not s.startswith('_')]
['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
->>> print i.next.__doc__
+>>> print(i.next.__doc__)
x.next() -> the next value, or raise StopIteration
>>> iter(i) is i
True
>>> gen = random.WichmannHill(42)
>>> while 1:
... for s in sets:
-... print "%s->%s" % (s, s.find()),
-... print
+... print("%s->%s" % (s, s.find()), end=' ')
+... print()
... if len(roots) > 1:
... s1 = gen.choice(roots)
... roots.remove(s1)
... s2 = gen.choice(roots)
... s1.union(s2)
-... print "merged", s1, "into", s2
+... print("merged", s1, "into", s2)
... else:
... break
A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
>>> result = m235()
>>> for i in range(3):
-... print firstn(result, 15)
+... print(firstn(result, 15))
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
>>> m235 = LazyList(m235())
>>> for i in range(5):
-... print [m235[j] for j in range(15*i, 15*(i+1))]
+... print([m235[j] for j in range(15*i, 15*(i+1))])
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
>>> it = m235()
>>> for i in range(5):
-... print firstn(it, 15)
+... print(firstn(it, 15))
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
... yield i
...
>>> g = f()
->>> print g.next()
+>>> print(g.next())
0
->>> print g.next()
+>>> print(g.next())
1
->>> print g.next()
+>>> print(g.next())
2
->>> print g.next()
+>>> print(g.next())
Traceback (most recent call last):
StopIteration
"""
possible use of conjoin, just to generate the full cross-product.
>>> for c in conjoin([lambda: iter((0, 1))] * 3):
-... print c
+... print(c)
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
>>> for n in range(10):
... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
-... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
+... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n)
0 1 True True
1 2 True True
2 4 True True
>>> for row2col in q.solve():
... count += 1
... if count <= LIMIT:
-... print "Solution", count
+... print("Solution", count)
... q.printsolution(row2col)
Solution 1
+-+-+-+-+-+-+-+-+
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+
->>> print count, "solutions in all."
+>>> print(count, "solutions in all.")
92 solutions in all.
And run a Knight's Tour on a 10x10 board. Note that there are about
>>> for x in k.solve():
... count += 1
... if count <= LIMIT:
-... print "Solution", count
+... print("Solution", count)
... k.printsolution(x)
... else:
... break
Sending a value into a started generator:
>>> def f():
-... print (yield 1)
+... print((yield 1))
... yield 2
>>> g = f()
>>> g.next()
>>> seq = []
>>> c = coroutine(seq)
>>> c.next()
->>> print seq
+>>> print(seq)
[]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10, 20]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10, 20, 30]
>>> def f():
... while True:
... try:
-... print (yield)
+... print((yield))
... except ValueError as v:
-... print "caught ValueError (%s)" % (v),
+... print("caught ValueError (%s)" % (v), end=' ')
>>> import sys
>>> g = f()
>>> g.next()
...
TypeError
->>> print g.gi_frame
+>>> print(g.gi_frame)
None
>>> g.send(2)
>>> def f():
... try: yield
... except GeneratorExit:
-... print "exiting"
+... print("exiting")
>>> g = f()
>>> g.next()
>>> def f():
... try: yield
... finally:
-... print "exiting"
+... print("exiting")
>>> g = f()
>>> g.next()
>>> def creator():
... r = yrange(5)
- ... print "creator", r.next()
+ ... print("creator", r.next())
... return r
>>> def caller():
... r = creator()
... for i in r:
- ... print "caller", i
+ ... print("caller", i)
>>> caller()
creator 0
caller 1
>>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected
True
- >>> print g.next.__doc__
+ >>> print(g.next.__doc__)
x.next() -> the next value, or raise StopIteration
>>> import types
>>> isinstance(g, types.GeneratorType)
>>> amounts = [120.15, 764.05, 823.14]
>>> for checknum, amount in izip(count(1200), amounts):
-... print 'Check %d is for $%.2f' % (checknum, amount)
-...
+... print('Check %d is for $%.2f' % (checknum, amount))
+...
Check 1200 is for $120.15
Check 1201 is for $764.05
Check 1202 is for $823.14
>>> import operator
>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
-... print cube
-...
+... print(cube)
+...
1
8
27
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
>>> for name in islice(reportlines, 3, None, 2):
-... print name.title()
-...
+... print(name.title())
+...
Alex
Laura
Martin
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
>>> for k, g in groupby(di, itemgetter(1)):
-... print k, map(itemgetter(0), g)
-...
+... print(k, map(itemgetter(0), g))
+...
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']
# same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
-... print map(operator.itemgetter(1), g)
-...
+... print(map(operator.itemgetter(1), g))
+...
[1]
[4, 5, 6]
[10]
... finally:
... for abc in range(10):
... continue
- ... print abc
+ ... print(abc)
>>> test()
9
isn't, there should be a syntax error.
>>> try:
- ... print 1
+ ... print(1)
... break
- ... print 2
+ ... print(2)
... finally:
- ... print 3
+ ... print(3)
Traceback (most recent call last):
...
SyntaxError: 'break' outside loop (<doctest test.test_syntax[42]>, line 3)
>>> r.has_header("Not-there")
False
- >>> print r.get_header("Not-there")
+ >>> print(r.get_header("Not-there"))
None
>>> r.get_header("Not-there", "default")
'default'
...
>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
>>> r = weakref.ref(obj)
->>> print r() is obj
+>>> print(r() is obj)
True
>>> import weakref
>>> o is o2
True
>>> del o, o2
->>> print r()
+>>> print(r())
None
>>> import weakref
>>> try:
... id2obj(a_id)
... except KeyError:
-... print 'OK'
+... print('OK')
... else:
-... print 'WeakValueDictionary error'
+... print('WeakValueDictionary error')
OK
"""
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
- >>> print ET.tostring(element)
+ >>> print(ET.tostring(element))
<html><body>text</body></html>
- >>> print ET.tostring(element, "ascii")
+ >>> print(ET.tostring(element, "ascii"))
<?xml version='1.0' encoding='ascii'?>
<html><body>text</body></html>
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
>>> document = xinclude_loader("C1.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C1
+ >>> print(serialize(ET, document)) # C1
<document>
<p>120 Mz is adequate for an average home user.</p>
<disclaimer>
>>> document = xinclude_loader("C2.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C2
+ >>> print(serialize(ET, document)) # C2
<document>
<p>This document has been accessed
324387 times.</p>
>>> document = xinclude_loader("C3.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C3
+ >>> print(serialize(ET, document)) # C3
<document>
<p>The following is the source of the "data.xml" resource:</p>
<example><?xml version='1.0'?>
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
- >>> print ET.tostring(element)
+ >>> print(ET.tostring(element))
<html><body>text</body></html>
- >>> print ET.tostring(element, "ascii")
+ >>> print(ET.tostring(element, "ascii"))
<?xml version='1.0' encoding='ascii'?>
<html><body>text</body></html>
>>> _, ids = ET.XMLID("<html><body>text</body></html>")