##// END OF EJS Templates
Fix tests for cpaste which no longer get error raised to them....
Thomas Kluyver -
Show More
@@ -1,455 +1,452 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from StringIO import StringIO
15 from StringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions begin
25 # Test functions begin
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 def test_rehashx():
27 def test_rehashx():
28 # clear up everything
28 # clear up everything
29 _ip = get_ipython()
29 _ip = get_ipython()
30 _ip.alias_manager.alias_table.clear()
30 _ip.alias_manager.alias_table.clear()
31 del _ip.db['syscmdlist']
31 del _ip.db['syscmdlist']
32
32
33 _ip.magic('rehashx')
33 _ip.magic('rehashx')
34 # Practically ALL ipython development systems will have more than 10 aliases
34 # Practically ALL ipython development systems will have more than 10 aliases
35
35
36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
37 for key, val in _ip.alias_manager.alias_table.iteritems():
37 for key, val in _ip.alias_manager.alias_table.iteritems():
38 # we must strip dots from alias names
38 # we must strip dots from alias names
39 nt.assert_true('.' not in key)
39 nt.assert_true('.' not in key)
40
40
41 # rehashx must fill up syscmdlist
41 # rehashx must fill up syscmdlist
42 scoms = _ip.db['syscmdlist']
42 scoms = _ip.db['syscmdlist']
43 yield (nt.assert_true, len(scoms) > 10)
43 yield (nt.assert_true, len(scoms) > 10)
44
44
45
45
46 def test_magic_parse_options():
46 def test_magic_parse_options():
47 """Test that we don't mangle paths when parsing magic options."""
47 """Test that we don't mangle paths when parsing magic options."""
48 ip = get_ipython()
48 ip = get_ipython()
49 path = 'c:\\x'
49 path = 'c:\\x'
50 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 opts = ip.parse_options('-f %s' % path,'f:')[0]
51 # argv splitting is os-dependent
51 # argv splitting is os-dependent
52 if os.name == 'posix':
52 if os.name == 'posix':
53 expected = 'c:x'
53 expected = 'c:x'
54 else:
54 else:
55 expected = path
55 expected = path
56 nt.assert_equals(opts['f'], expected)
56 nt.assert_equals(opts['f'], expected)
57
57
58
58
59 def doctest_hist_f():
59 def doctest_hist_f():
60 """Test %hist -f with temporary filename.
60 """Test %hist -f with temporary filename.
61
61
62 In [9]: import tempfile
62 In [9]: import tempfile
63
63
64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
65
65
66 In [11]: %hist -nl -f $tfile 3
66 In [11]: %hist -nl -f $tfile 3
67
67
68 In [13]: import os; os.unlink(tfile)
68 In [13]: import os; os.unlink(tfile)
69 """
69 """
70
70
71
71
72 def doctest_hist_r():
72 def doctest_hist_r():
73 """Test %hist -r
73 """Test %hist -r
74
74
75 XXX - This test is not recording the output correctly. For some reason, in
75 XXX - This test is not recording the output correctly. For some reason, in
76 testing mode the raw history isn't getting populated. No idea why.
76 testing mode the raw history isn't getting populated. No idea why.
77 Disabling the output checking for now, though at least we do run it.
77 Disabling the output checking for now, though at least we do run it.
78
78
79 In [1]: 'hist' in _ip.lsmagic()
79 In [1]: 'hist' in _ip.lsmagic()
80 Out[1]: True
80 Out[1]: True
81
81
82 In [2]: x=1
82 In [2]: x=1
83
83
84 In [3]: %hist -rl 2
84 In [3]: %hist -rl 2
85 x=1 # random
85 x=1 # random
86 %hist -r 2
86 %hist -r 2
87 """
87 """
88
88
89 def doctest_hist_op():
89 def doctest_hist_op():
90 """Test %hist -op
90 """Test %hist -op
91
91
92 In [1]: class b(float):
92 In [1]: class b(float):
93 ...: pass
93 ...: pass
94 ...:
94 ...:
95
95
96 In [2]: class s(object):
96 In [2]: class s(object):
97 ...: def __str__(self):
97 ...: def __str__(self):
98 ...: return 's'
98 ...: return 's'
99 ...:
99 ...:
100
100
101 In [3]:
101 In [3]:
102
102
103 In [4]: class r(b):
103 In [4]: class r(b):
104 ...: def __repr__(self):
104 ...: def __repr__(self):
105 ...: return 'r'
105 ...: return 'r'
106 ...:
106 ...:
107
107
108 In [5]: class sr(s,r): pass
108 In [5]: class sr(s,r): pass
109 ...:
109 ...:
110
110
111 In [6]:
111 In [6]:
112
112
113 In [7]: bb=b()
113 In [7]: bb=b()
114
114
115 In [8]: ss=s()
115 In [8]: ss=s()
116
116
117 In [9]: rr=r()
117 In [9]: rr=r()
118
118
119 In [10]: ssrr=sr()
119 In [10]: ssrr=sr()
120
120
121 In [11]: 4.5
121 In [11]: 4.5
122 Out[11]: 4.5
122 Out[11]: 4.5
123
123
124 In [12]: str(ss)
124 In [12]: str(ss)
125 Out[12]: 's'
125 Out[12]: 's'
126
126
127 In [13]:
127 In [13]:
128
128
129 In [14]: %hist -op
129 In [14]: %hist -op
130 >>> class b:
130 >>> class b:
131 ... pass
131 ... pass
132 ...
132 ...
133 >>> class s(b):
133 >>> class s(b):
134 ... def __str__(self):
134 ... def __str__(self):
135 ... return 's'
135 ... return 's'
136 ...
136 ...
137 >>>
137 >>>
138 >>> class r(b):
138 >>> class r(b):
139 ... def __repr__(self):
139 ... def __repr__(self):
140 ... return 'r'
140 ... return 'r'
141 ...
141 ...
142 >>> class sr(s,r): pass
142 >>> class sr(s,r): pass
143 >>>
143 >>>
144 >>> bb=b()
144 >>> bb=b()
145 >>> ss=s()
145 >>> ss=s()
146 >>> rr=r()
146 >>> rr=r()
147 >>> ssrr=sr()
147 >>> ssrr=sr()
148 >>> 4.5
148 >>> 4.5
149 4.5
149 4.5
150 >>> str(ss)
150 >>> str(ss)
151 's'
151 's'
152 >>>
152 >>>
153 """
153 """
154
154
155 def test_macro():
155 def test_macro():
156 ip = get_ipython()
156 ip = get_ipython()
157 ip.history_manager.reset() # Clear any existing history.
157 ip.history_manager.reset() # Clear any existing history.
158 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
158 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
159 for i, cmd in enumerate(cmds, start=1):
159 for i, cmd in enumerate(cmds, start=1):
160 ip.history_manager.store_inputs(i, cmd)
160 ip.history_manager.store_inputs(i, cmd)
161 ip.magic("macro test 1-3")
161 ip.magic("macro test 1-3")
162 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
163
163
164 # List macros.
164 # List macros.
165 assert "test" in ip.magic("macro")
165 assert "test" in ip.magic("macro")
166
166
167 def test_macro_run():
167 def test_macro_run():
168 """Test that we can run a multi-line macro successfully."""
168 """Test that we can run a multi-line macro successfully."""
169 ip = get_ipython()
169 ip = get_ipython()
170 ip.history_manager.reset()
170 ip.history_manager.reset()
171 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
171 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
172 "%macro test 2-3"]
172 "%macro test 2-3"]
173 for cmd in cmds:
173 for cmd in cmds:
174 ip.run_cell(cmd, store_history=True)
174 ip.run_cell(cmd, store_history=True)
175 nt.assert_equal(ip.user_ns["test"].value,
175 nt.assert_equal(ip.user_ns["test"].value,
176 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
176 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
177 with tt.AssertPrints("12"):
177 with tt.AssertPrints("12"):
178 ip.run_cell("test")
178 ip.run_cell("test")
179 with tt.AssertPrints("13"):
179 with tt.AssertPrints("13"):
180 ip.run_cell("test")
180 ip.run_cell("test")
181
181
182
182
183 # XXX failing for now, until we get clearcmd out of quarantine. But we should
183 # XXX failing for now, until we get clearcmd out of quarantine. But we should
184 # fix this and revert the skip to happen only if numpy is not around.
184 # fix this and revert the skip to happen only if numpy is not around.
185 #@dec.skipif_not_numpy
185 #@dec.skipif_not_numpy
186 @dec.skip_known_failure
186 @dec.skip_known_failure
187 def test_numpy_clear_array_undec():
187 def test_numpy_clear_array_undec():
188 from IPython.extensions import clearcmd
188 from IPython.extensions import clearcmd
189
189
190 _ip.ex('import numpy as np')
190 _ip.ex('import numpy as np')
191 _ip.ex('a = np.empty(2)')
191 _ip.ex('a = np.empty(2)')
192 yield (nt.assert_true, 'a' in _ip.user_ns)
192 yield (nt.assert_true, 'a' in _ip.user_ns)
193 _ip.magic('clear array')
193 _ip.magic('clear array')
194 yield (nt.assert_false, 'a' in _ip.user_ns)
194 yield (nt.assert_false, 'a' in _ip.user_ns)
195
195
196
196
197 # Multiple tests for clipboard pasting
197 # Multiple tests for clipboard pasting
198 @dec.parametric
198 @dec.parametric
199 def test_paste():
199 def test_paste():
200 _ip = get_ipython()
200 _ip = get_ipython()
201 def paste(txt, flags='-q'):
201 def paste(txt, flags='-q'):
202 """Paste input text, by default in quiet mode"""
202 """Paste input text, by default in quiet mode"""
203 hooks.clipboard_get = lambda : txt
203 hooks.clipboard_get = lambda : txt
204 _ip.magic('paste '+flags)
204 _ip.magic('paste '+flags)
205
205
206 # Inject fake clipboard hook but save original so we can restore it later
206 # Inject fake clipboard hook but save original so we can restore it later
207 hooks = _ip.hooks
207 hooks = _ip.hooks
208 user_ns = _ip.user_ns
208 user_ns = _ip.user_ns
209 original_clip = hooks.clipboard_get
209 original_clip = hooks.clipboard_get
210
210
211 try:
211 try:
212 # Run tests with fake clipboard function
212 # Run tests with fake clipboard function
213 user_ns.pop('x', None)
213 user_ns.pop('x', None)
214 paste('x=1')
214 paste('x=1')
215 yield nt.assert_equal(user_ns['x'], 1)
215 yield nt.assert_equal(user_ns['x'], 1)
216
216
217 user_ns.pop('x', None)
217 user_ns.pop('x', None)
218 paste('>>> x=2')
218 paste('>>> x=2')
219 yield nt.assert_equal(user_ns['x'], 2)
219 yield nt.assert_equal(user_ns['x'], 2)
220
220
221 paste("""
221 paste("""
222 >>> x = [1,2,3]
222 >>> x = [1,2,3]
223 >>> y = []
223 >>> y = []
224 >>> for i in x:
224 >>> for i in x:
225 ... y.append(i**2)
225 ... y.append(i**2)
226 ...
226 ...
227 """)
227 """)
228 yield nt.assert_equal(user_ns['x'], [1,2,3])
228 yield nt.assert_equal(user_ns['x'], [1,2,3])
229 yield nt.assert_equal(user_ns['y'], [1,4,9])
229 yield nt.assert_equal(user_ns['y'], [1,4,9])
230
230
231 # Now, test that paste -r works
231 # Now, test that paste -r works
232 user_ns.pop('x', None)
232 user_ns.pop('x', None)
233 yield nt.assert_false('x' in user_ns)
233 yield nt.assert_false('x' in user_ns)
234 _ip.magic('paste -r')
234 _ip.magic('paste -r')
235 yield nt.assert_equal(user_ns['x'], [1,2,3])
235 yield nt.assert_equal(user_ns['x'], [1,2,3])
236
236
237 # Also test paste echoing, by temporarily faking the writer
237 # Also test paste echoing, by temporarily faking the writer
238 w = StringIO()
238 w = StringIO()
239 writer = _ip.write
239 writer = _ip.write
240 _ip.write = w.write
240 _ip.write = w.write
241 code = """
241 code = """
242 a = 100
242 a = 100
243 b = 200"""
243 b = 200"""
244 try:
244 try:
245 paste(code,'')
245 paste(code,'')
246 out = w.getvalue()
246 out = w.getvalue()
247 finally:
247 finally:
248 _ip.write = writer
248 _ip.write = writer
249 yield nt.assert_equal(user_ns['a'], 100)
249 yield nt.assert_equal(user_ns['a'], 100)
250 yield nt.assert_equal(user_ns['b'], 200)
250 yield nt.assert_equal(user_ns['b'], 200)
251 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
251 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
252
252
253 finally:
253 finally:
254 # Restore original hook
254 # Restore original hook
255 hooks.clipboard_get = original_clip
255 hooks.clipboard_get = original_clip
256
256
257
257
258 def test_time():
258 def test_time():
259 _ip.magic('time None')
259 _ip.magic('time None')
260
260
261
261
262 @py3compat.doctest_refactor_print
262 @py3compat.doctest_refactor_print
263 def doctest_time():
263 def doctest_time():
264 """
264 """
265 In [10]: %time None
265 In [10]: %time None
266 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
266 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
267 Wall time: 0.00 s
267 Wall time: 0.00 s
268
268
269 In [11]: def f(kmjy):
269 In [11]: def f(kmjy):
270 ....: %time print 2*kmjy
270 ....: %time print 2*kmjy
271
271
272 In [12]: f(3)
272 In [12]: f(3)
273 6
273 6
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
274 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 Wall time: 0.00 s
275 Wall time: 0.00 s
276 """
276 """
277
277
278
278
279 def test_doctest_mode():
279 def test_doctest_mode():
280 "Toggle doctest_mode twice, it should be a no-op and run without error"
280 "Toggle doctest_mode twice, it should be a no-op and run without error"
281 _ip.magic('doctest_mode')
281 _ip.magic('doctest_mode')
282 _ip.magic('doctest_mode')
282 _ip.magic('doctest_mode')
283
283
284
284
285 def test_parse_options():
285 def test_parse_options():
286 """Tests for basic options parsing in magics."""
286 """Tests for basic options parsing in magics."""
287 # These are only the most minimal of tests, more should be added later. At
287 # These are only the most minimal of tests, more should be added later. At
288 # the very least we check that basic text/unicode calls work OK.
288 # the very least we check that basic text/unicode calls work OK.
289 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
289 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
290 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
290 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
291
291
292
292
293 def test_dirops():
293 def test_dirops():
294 """Test various directory handling operations."""
294 """Test various directory handling operations."""
295 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
295 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
296 curpath = os.getcwdu
296 curpath = os.getcwdu
297 startdir = os.getcwdu()
297 startdir = os.getcwdu()
298 ipdir = _ip.ipython_dir
298 ipdir = _ip.ipython_dir
299 try:
299 try:
300 _ip.magic('cd "%s"' % ipdir)
300 _ip.magic('cd "%s"' % ipdir)
301 nt.assert_equal(curpath(), ipdir)
301 nt.assert_equal(curpath(), ipdir)
302 _ip.magic('cd -')
302 _ip.magic('cd -')
303 nt.assert_equal(curpath(), startdir)
303 nt.assert_equal(curpath(), startdir)
304 _ip.magic('pushd "%s"' % ipdir)
304 _ip.magic('pushd "%s"' % ipdir)
305 nt.assert_equal(curpath(), ipdir)
305 nt.assert_equal(curpath(), ipdir)
306 _ip.magic('popd')
306 _ip.magic('popd')
307 nt.assert_equal(curpath(), startdir)
307 nt.assert_equal(curpath(), startdir)
308 finally:
308 finally:
309 os.chdir(startdir)
309 os.chdir(startdir)
310
310
311
311
312 def check_cpaste(code, should_fail=False):
312 def check_cpaste(code, should_fail=False):
313 """Execute code via 'cpaste' and ensure it was executed, unless
313 """Execute code via 'cpaste' and ensure it was executed, unless
314 should_fail is set.
314 should_fail is set.
315 """
315 """
316 _ip.user_ns['code_ran'] = False
316 _ip.user_ns['code_ran'] = False
317
317
318 src = StringIO()
318 src = StringIO()
319 src.encoding = None # IPython expects stdin to have an encoding attribute
319 src.encoding = None # IPython expects stdin to have an encoding attribute
320 src.write('\n')
320 src.write('\n')
321 src.write(code)
321 src.write(code)
322 src.write('\n--\n')
322 src.write('\n--\n')
323 src.seek(0)
323 src.seek(0)
324
324
325 stdin_save = sys.stdin
325 stdin_save = sys.stdin
326 sys.stdin = src
326 sys.stdin = src
327
327
328 try:
328 try:
329 _ip.magic('cpaste')
329 context = tt.AssertPrints if should_fail else tt.AssertNotPrints
330 except:
330 with context("Traceback (most recent call last)"):
331 _ip.magic('cpaste')
332
331 if not should_fail:
333 if not should_fail:
332 raise AssertionError("Failure not expected : '%s'" %
334 assert _ip.user_ns['code_ran']
333 code)
334 else:
335 assert _ip.user_ns['code_ran']
336 if should_fail:
337 raise AssertionError("Failure expected : '%s'" % code)
338 finally:
335 finally:
339 sys.stdin = stdin_save
336 sys.stdin = stdin_save
340
337
341
338
342 def test_cpaste():
339 def test_cpaste():
343 """Test cpaste magic"""
340 """Test cpaste magic"""
344
341
345 def run():
342 def run():
346 """Marker function: sets a flag when executed.
343 """Marker function: sets a flag when executed.
347 """
344 """
348 _ip.user_ns['code_ran'] = True
345 _ip.user_ns['code_ran'] = True
349 return 'run' # return string so '+ run()' doesn't result in success
346 return 'run' # return string so '+ run()' doesn't result in success
350
347
351 tests = {'pass': ["> > > run()",
348 tests = {'pass': ["> > > run()",
352 ">>> > run()",
349 ">>> > run()",
353 "+++ run()",
350 "+++ run()",
354 "++ run()",
351 "++ run()",
355 " >>> run()"],
352 " >>> run()"],
356
353
357 'fail': ["+ + run()",
354 'fail': ["+ + run()",
358 " ++ run()"]}
355 " ++ run()"]}
359
356
360 _ip.user_ns['run'] = run
357 _ip.user_ns['run'] = run
361
358
362 for code in tests['pass']:
359 for code in tests['pass']:
363 check_cpaste(code)
360 check_cpaste(code)
364
361
365 for code in tests['fail']:
362 for code in tests['fail']:
366 check_cpaste(code, should_fail=True)
363 check_cpaste(code, should_fail=True)
367
364
368 def test_xmode():
365 def test_xmode():
369 # Calling xmode three times should be a no-op
366 # Calling xmode three times should be a no-op
370 xmode = _ip.InteractiveTB.mode
367 xmode = _ip.InteractiveTB.mode
371 for i in range(3):
368 for i in range(3):
372 _ip.magic("xmode")
369 _ip.magic("xmode")
373 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
370 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
374
371
375 def test_reset_hard():
372 def test_reset_hard():
376 monitor = []
373 monitor = []
377 class A(object):
374 class A(object):
378 def __del__(self):
375 def __del__(self):
379 monitor.append(1)
376 monitor.append(1)
380 def __repr__(self):
377 def __repr__(self):
381 return "<A instance>"
378 return "<A instance>"
382
379
383 _ip.user_ns["a"] = A()
380 _ip.user_ns["a"] = A()
384 _ip.run_cell("a")
381 _ip.run_cell("a")
385
382
386 nt.assert_equal(monitor, [])
383 nt.assert_equal(monitor, [])
387 _ip.magic_reset("-f")
384 _ip.magic_reset("-f")
388 nt.assert_equal(monitor, [1])
385 nt.assert_equal(monitor, [1])
389
386
390 class TestXdel(tt.TempFileMixin):
387 class TestXdel(tt.TempFileMixin):
391 def test_xdel(self):
388 def test_xdel(self):
392 """Test that references from %run are cleared by xdel."""
389 """Test that references from %run are cleared by xdel."""
393 src = ("class A(object):\n"
390 src = ("class A(object):\n"
394 " monitor = []\n"
391 " monitor = []\n"
395 " def __del__(self):\n"
392 " def __del__(self):\n"
396 " self.monitor.append(1)\n"
393 " self.monitor.append(1)\n"
397 "a = A()\n")
394 "a = A()\n")
398 self.mktmp(src)
395 self.mktmp(src)
399 # %run creates some hidden references...
396 # %run creates some hidden references...
400 _ip.magic("run %s" % self.fname)
397 _ip.magic("run %s" % self.fname)
401 # ... as does the displayhook.
398 # ... as does the displayhook.
402 _ip.run_cell("a")
399 _ip.run_cell("a")
403
400
404 monitor = _ip.user_ns["A"].monitor
401 monitor = _ip.user_ns["A"].monitor
405 nt.assert_equal(monitor, [])
402 nt.assert_equal(monitor, [])
406
403
407 _ip.magic("xdel a")
404 _ip.magic("xdel a")
408
405
409 # Check that a's __del__ method has been called.
406 # Check that a's __del__ method has been called.
410 nt.assert_equal(monitor, [1])
407 nt.assert_equal(monitor, [1])
411
408
412 def doctest_who():
409 def doctest_who():
413 """doctest for %who
410 """doctest for %who
414
411
415 In [1]: %reset -f
412 In [1]: %reset -f
416
413
417 In [2]: alpha = 123
414 In [2]: alpha = 123
418
415
419 In [3]: beta = 'beta'
416 In [3]: beta = 'beta'
420
417
421 In [4]: %who int
418 In [4]: %who int
422 alpha
419 alpha
423
420
424 In [5]: %who str
421 In [5]: %who str
425 beta
422 beta
426
423
427 In [6]: %whos
424 In [6]: %whos
428 Variable Type Data/Info
425 Variable Type Data/Info
429 ----------------------------
426 ----------------------------
430 alpha int 123
427 alpha int 123
431 beta str beta
428 beta str beta
432
429
433 In [7]: %who_ls
430 In [7]: %who_ls
434 Out[7]: ['alpha', 'beta']
431 Out[7]: ['alpha', 'beta']
435 """
432 """
436
433
437 @py3compat.u_format
434 @py3compat.u_format
438 def doctest_precision():
435 def doctest_precision():
439 """doctest for %precision
436 """doctest for %precision
440
437
441 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
438 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
442
439
443 In [2]: %precision 5
440 In [2]: %precision 5
444 Out[2]: {u}'%.5f'
441 Out[2]: {u}'%.5f'
445
442
446 In [3]: f.float_format
443 In [3]: f.float_format
447 Out[3]: {u}'%.5f'
444 Out[3]: {u}'%.5f'
448
445
449 In [4]: %precision %e
446 In [4]: %precision %e
450 Out[4]: {u}'%e'
447 Out[4]: {u}'%e'
451
448
452 In [5]: f(3.1415927)
449 In [5]: f(3.1415927)
453 Out[5]: {u}'3.141593e+00'
450 Out[5]: {u}'3.141593e+00'
454 """
451 """
455
452
General Comments 0
You need to be logged in to leave comments. Login now