namespace.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. """Implementation of namespace-related magic functions.
  2. """
  3. from __future__ import print_function
  4. #-----------------------------------------------------------------------------
  5. # Copyright (c) 2012 The IPython Development Team.
  6. #
  7. # Distributed under the terms of the Modified BSD License.
  8. #
  9. # The full license is in the file COPYING.txt, distributed with this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. # Stdlib
  15. import gc
  16. import re
  17. import sys
  18. # Our own packages
  19. from IPython.core import page
  20. from IPython.core.error import StdinNotImplementedError, UsageError
  21. from IPython.core.magic import Magics, magics_class, line_magic
  22. from IPython.testing.skipdoctest import skip_doctest
  23. from IPython.utils.encoding import DEFAULT_ENCODING
  24. from IPython.utils.openpy import read_py_file
  25. from IPython.utils.path import get_py_filename
  26. from IPython.utils.py3compat import unicode_type
  27. #-----------------------------------------------------------------------------
  28. # Magic implementation classes
  29. #-----------------------------------------------------------------------------
  30. @magics_class
  31. class NamespaceMagics(Magics):
  32. """Magics to manage various aspects of the user's namespace.
  33. These include listing variables, introspecting into them, etc.
  34. """
  35. @line_magic
  36. def pinfo(self, parameter_s='', namespaces=None):
  37. """Provide detailed information about an object.
  38. '%pinfo object' is just a synonym for object? or ?object."""
  39. #print 'pinfo par: <%s>' % parameter_s # dbg
  40. # detail_level: 0 -> obj? , 1 -> obj??
  41. detail_level = 0
  42. # We need to detect if we got called as 'pinfo pinfo foo', which can
  43. # happen if the user types 'pinfo foo?' at the cmd line.
  44. pinfo,qmark1,oname,qmark2 = \
  45. re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
  46. if pinfo or qmark1 or qmark2:
  47. detail_level = 1
  48. if "*" in oname:
  49. self.psearch(oname)
  50. else:
  51. self.shell._inspect('pinfo', oname, detail_level=detail_level,
  52. namespaces=namespaces)
  53. @line_magic
  54. def pinfo2(self, parameter_s='', namespaces=None):
  55. """Provide extra detailed information about an object.
  56. '%pinfo2 object' is just a synonym for object?? or ??object."""
  57. self.shell._inspect('pinfo', parameter_s, detail_level=1,
  58. namespaces=namespaces)
  59. @skip_doctest
  60. @line_magic
  61. def pdef(self, parameter_s='', namespaces=None):
  62. """Print the call signature for any callable object.
  63. If the object is a class, print the constructor information.
  64. Examples
  65. --------
  66. ::
  67. In [3]: %pdef urllib.urlopen
  68. urllib.urlopen(url, data=None, proxies=None)
  69. """
  70. self.shell._inspect('pdef',parameter_s, namespaces)
  71. @line_magic
  72. def pdoc(self, parameter_s='', namespaces=None):
  73. """Print the docstring for an object.
  74. If the given object is a class, it will print both the class and the
  75. constructor docstrings."""
  76. self.shell._inspect('pdoc',parameter_s, namespaces)
  77. @line_magic
  78. def psource(self, parameter_s='', namespaces=None):
  79. """Print (or run through pager) the source code for an object."""
  80. if not parameter_s:
  81. raise UsageError('Missing object name.')
  82. self.shell._inspect('psource',parameter_s, namespaces)
  83. @line_magic
  84. def pfile(self, parameter_s='', namespaces=None):
  85. """Print (or run through pager) the file where an object is defined.
  86. The file opens at the line where the object definition begins. IPython
  87. will honor the environment variable PAGER if set, and otherwise will
  88. do its best to print the file in a convenient form.
  89. If the given argument is not an object currently defined, IPython will
  90. try to interpret it as a filename (automatically adding a .py extension
  91. if needed). You can thus use %pfile as a syntax highlighting code
  92. viewer."""
  93. # first interpret argument as an object name
  94. out = self.shell._inspect('pfile',parameter_s, namespaces)
  95. # if not, try the input as a filename
  96. if out == 'not found':
  97. try:
  98. filename = get_py_filename(parameter_s)
  99. except IOError as msg:
  100. print(msg)
  101. return
  102. page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
  103. @line_magic
  104. def psearch(self, parameter_s=''):
  105. """Search for object in namespaces by wildcard.
  106. %psearch [options] PATTERN [OBJECT TYPE]
  107. Note: ? can be used as a synonym for %psearch, at the beginning or at
  108. the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
  109. rest of the command line must be unchanged (options come first), so
  110. for example the following forms are equivalent
  111. %psearch -i a* function
  112. -i a* function?
  113. ?-i a* function
  114. Arguments:
  115. PATTERN
  116. where PATTERN is a string containing * as a wildcard similar to its
  117. use in a shell. The pattern is matched in all namespaces on the
  118. search path. By default objects starting with a single _ are not
  119. matched, many IPython generated objects have a single
  120. underscore. The default is case insensitive matching. Matching is
  121. also done on the attributes of objects and not only on the objects
  122. in a module.
  123. [OBJECT TYPE]
  124. Is the name of a python type from the types module. The name is
  125. given in lowercase without the ending type, ex. StringType is
  126. written string. By adding a type here only objects matching the
  127. given type are matched. Using all here makes the pattern match all
  128. types (this is the default).
  129. Options:
  130. -a: makes the pattern match even objects whose names start with a
  131. single underscore. These names are normally omitted from the
  132. search.
  133. -i/-c: make the pattern case insensitive/sensitive. If neither of
  134. these options are given, the default is read from your configuration
  135. file, with the option ``InteractiveShell.wildcards_case_sensitive``.
  136. If this option is not specified in your configuration file, IPython's
  137. internal default is to do a case sensitive search.
  138. -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
  139. specify can be searched in any of the following namespaces:
  140. 'builtin', 'user', 'user_global','internal', 'alias', where
  141. 'builtin' and 'user' are the search defaults. Note that you should
  142. not use quotes when specifying namespaces.
  143. 'Builtin' contains the python module builtin, 'user' contains all
  144. user data, 'alias' only contain the shell aliases and no python
  145. objects, 'internal' contains objects used by IPython. The
  146. 'user_global' namespace is only used by embedded IPython instances,
  147. and it contains module-level globals. You can add namespaces to the
  148. search with -s or exclude them with -e (these options can be given
  149. more than once).
  150. Examples
  151. --------
  152. ::
  153. %psearch a* -> objects beginning with an a
  154. %psearch -e builtin a* -> objects NOT in the builtin space starting in a
  155. %psearch a* function -> all functions beginning with an a
  156. %psearch re.e* -> objects beginning with an e in module re
  157. %psearch r*.e* -> objects that start with e in modules starting in r
  158. %psearch r*.* string -> all strings in modules beginning with r
  159. Case sensitive search::
  160. %psearch -c a* list all object beginning with lower case a
  161. Show objects beginning with a single _::
  162. %psearch -a _* list objects beginning with a single underscore
  163. """
  164. try:
  165. parameter_s.encode('ascii')
  166. except UnicodeEncodeError:
  167. print('Python identifiers can only contain ascii characters.')
  168. return
  169. # default namespaces to be searched
  170. def_search = ['user_local', 'user_global', 'builtin']
  171. # Process options/args
  172. opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
  173. opt = opts.get
  174. shell = self.shell
  175. psearch = shell.inspector.psearch
  176. # select case options
  177. if 'i' in opts:
  178. ignore_case = True
  179. elif 'c' in opts:
  180. ignore_case = False
  181. else:
  182. ignore_case = not shell.wildcards_case_sensitive
  183. # Build list of namespaces to search from user options
  184. def_search.extend(opt('s',[]))
  185. ns_exclude = ns_exclude=opt('e',[])
  186. ns_search = [nm for nm in def_search if nm not in ns_exclude]
  187. # Call the actual search
  188. try:
  189. psearch(args,shell.ns_table,ns_search,
  190. show_all=opt('a'),ignore_case=ignore_case)
  191. except:
  192. shell.showtraceback()
  193. @skip_doctest
  194. @line_magic
  195. def who_ls(self, parameter_s=''):
  196. """Return a sorted list of all interactive variables.
  197. If arguments are given, only variables of types matching these
  198. arguments are returned.
  199. Examples
  200. --------
  201. Define two variables and list them with who_ls::
  202. In [1]: alpha = 123
  203. In [2]: beta = 'test'
  204. In [3]: %who_ls
  205. Out[3]: ['alpha', 'beta']
  206. In [4]: %who_ls int
  207. Out[4]: ['alpha']
  208. In [5]: %who_ls str
  209. Out[5]: ['beta']
  210. """
  211. user_ns = self.shell.user_ns
  212. user_ns_hidden = self.shell.user_ns_hidden
  213. nonmatching = object() # This can never be in user_ns
  214. out = [ i for i in user_ns
  215. if not i.startswith('_') \
  216. and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
  217. typelist = parameter_s.split()
  218. if typelist:
  219. typeset = set(typelist)
  220. out = [i for i in out if type(user_ns[i]).__name__ in typeset]
  221. out.sort()
  222. return out
  223. @skip_doctest
  224. @line_magic
  225. def who(self, parameter_s=''):
  226. """Print all interactive variables, with some minimal formatting.
  227. If any arguments are given, only variables whose type matches one of
  228. these are printed. For example::
  229. %who function str
  230. will only list functions and strings, excluding all other types of
  231. variables. To find the proper type names, simply use type(var) at a
  232. command line to see how python prints type names. For example:
  233. ::
  234. In [1]: type('hello')\\
  235. Out[1]: <type 'str'>
  236. indicates that the type name for strings is 'str'.
  237. ``%who`` always excludes executed names loaded through your configuration
  238. file and things which are internal to IPython.
  239. This is deliberate, as typically you may load many modules and the
  240. purpose of %who is to show you only what you've manually defined.
  241. Examples
  242. --------
  243. Define two variables and list them with who::
  244. In [1]: alpha = 123
  245. In [2]: beta = 'test'
  246. In [3]: %who
  247. alpha beta
  248. In [4]: %who int
  249. alpha
  250. In [5]: %who str
  251. beta
  252. """
  253. varlist = self.who_ls(parameter_s)
  254. if not varlist:
  255. if parameter_s:
  256. print('No variables match your requested type.')
  257. else:
  258. print('Interactive namespace is empty.')
  259. return
  260. # if we have variables, move on...
  261. count = 0
  262. for i in varlist:
  263. print(i+'\t', end=' ')
  264. count += 1
  265. if count > 8:
  266. count = 0
  267. print()
  268. print()
  269. @skip_doctest
  270. @line_magic
  271. def whos(self, parameter_s=''):
  272. """Like %who, but gives some extra information about each variable.
  273. The same type filtering of %who can be applied here.
  274. For all variables, the type is printed. Additionally it prints:
  275. - For {},[],(): their length.
  276. - For numpy arrays, a summary with shape, number of
  277. elements, typecode and size in memory.
  278. - Everything else: a string representation, snipping their middle if
  279. too long.
  280. Examples
  281. --------
  282. Define two variables and list them with whos::
  283. In [1]: alpha = 123
  284. In [2]: beta = 'test'
  285. In [3]: %whos
  286. Variable Type Data/Info
  287. --------------------------------
  288. alpha int 123
  289. beta str test
  290. """
  291. varnames = self.who_ls(parameter_s)
  292. if not varnames:
  293. if parameter_s:
  294. print('No variables match your requested type.')
  295. else:
  296. print('Interactive namespace is empty.')
  297. return
  298. # if we have variables, move on...
  299. # for these types, show len() instead of data:
  300. seq_types = ['dict', 'list', 'tuple']
  301. # for numpy arrays, display summary info
  302. ndarray_type = None
  303. if 'numpy' in sys.modules:
  304. try:
  305. from numpy import ndarray
  306. except ImportError:
  307. pass
  308. else:
  309. ndarray_type = ndarray.__name__
  310. # Find all variable names and types so we can figure out column sizes
  311. # some types are well known and can be shorter
  312. abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
  313. def type_name(v):
  314. tn = type(v).__name__
  315. return abbrevs.get(tn,tn)
  316. varlist = [self.shell.user_ns[n] for n in varnames]
  317. typelist = []
  318. for vv in varlist:
  319. tt = type_name(vv)
  320. if tt=='instance':
  321. typelist.append( abbrevs.get(str(vv.__class__),
  322. str(vv.__class__)))
  323. else:
  324. typelist.append(tt)
  325. # column labels and # of spaces as separator
  326. varlabel = 'Variable'
  327. typelabel = 'Type'
  328. datalabel = 'Data/Info'
  329. colsep = 3
  330. # variable format strings
  331. vformat = "{0:<{varwidth}}{1:<{typewidth}}"
  332. aformat = "%s: %s elems, type `%s`, %s bytes"
  333. # find the size of the columns to format the output nicely
  334. varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
  335. typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
  336. # table header
  337. print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
  338. ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
  339. # and the table itself
  340. kb = 1024
  341. Mb = 1048576 # kb**2
  342. for vname,var,vtype in zip(varnames,varlist,typelist):
  343. print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
  344. if vtype in seq_types:
  345. print("n="+str(len(var)))
  346. elif vtype == ndarray_type:
  347. vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
  348. if vtype==ndarray_type:
  349. # numpy
  350. vsize = var.size
  351. vbytes = vsize*var.itemsize
  352. vdtype = var.dtype
  353. if vbytes < 100000:
  354. print(aformat % (vshape, vsize, vdtype, vbytes))
  355. else:
  356. print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
  357. if vbytes < Mb:
  358. print('(%s kb)' % (vbytes/kb,))
  359. else:
  360. print('(%s Mb)' % (vbytes/Mb,))
  361. else:
  362. try:
  363. vstr = str(var)
  364. except UnicodeEncodeError:
  365. vstr = unicode_type(var).encode(DEFAULT_ENCODING,
  366. 'backslashreplace')
  367. except:
  368. vstr = "<object with id %d (str() failed)>" % id(var)
  369. vstr = vstr.replace('\n', '\\n')
  370. if len(vstr) < 50:
  371. print(vstr)
  372. else:
  373. print(vstr[:25] + "<...>" + vstr[-25:])
  374. @line_magic
  375. def reset(self, parameter_s=''):
  376. """Resets the namespace by removing all names defined by the user, if
  377. called without arguments, or by removing some types of objects, such
  378. as everything currently in IPython's In[] and Out[] containers (see
  379. the parameters for details).
  380. Parameters
  381. ----------
  382. -f : force reset without asking for confirmation.
  383. -s : 'Soft' reset: Only clears your namespace, leaving history intact.
  384. References to objects may be kept. By default (without this option),
  385. we do a 'hard' reset, giving you a new session and removing all
  386. references to objects from the current session.
  387. in : reset input history
  388. out : reset output history
  389. dhist : reset directory history
  390. array : reset only variables that are NumPy arrays
  391. See Also
  392. --------
  393. reset_selective : invoked as ``%reset_selective``
  394. Examples
  395. --------
  396. ::
  397. In [6]: a = 1
  398. In [7]: a
  399. Out[7]: 1
  400. In [8]: 'a' in _ip.user_ns
  401. Out[8]: True
  402. In [9]: %reset -f
  403. In [1]: 'a' in _ip.user_ns
  404. Out[1]: False
  405. In [2]: %reset -f in
  406. Flushing input history
  407. In [3]: %reset -f dhist in
  408. Flushing directory history
  409. Flushing input history
  410. Notes
  411. -----
  412. Calling this magic from clients that do not implement standard input,
  413. such as the ipython notebook interface, will reset the namespace
  414. without confirmation.
  415. """
  416. opts, args = self.parse_options(parameter_s,'sf', mode='list')
  417. if 'f' in opts:
  418. ans = True
  419. else:
  420. try:
  421. ans = self.shell.ask_yes_no(
  422. "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
  423. default='n')
  424. except StdinNotImplementedError:
  425. ans = True
  426. if not ans:
  427. print('Nothing done.')
  428. return
  429. if 's' in opts: # Soft reset
  430. user_ns = self.shell.user_ns
  431. for i in self.who_ls():
  432. del(user_ns[i])
  433. elif len(args) == 0: # Hard reset
  434. self.shell.reset(new_session = False)
  435. # reset in/out/dhist/array: previously extensinions/clearcmd.py
  436. ip = self.shell
  437. user_ns = self.shell.user_ns # local lookup, heavily used
  438. for target in args:
  439. target = target.lower() # make matches case insensitive
  440. if target == 'out':
  441. print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
  442. self.shell.displayhook.flush()
  443. elif target == 'in':
  444. print("Flushing input history")
  445. pc = self.shell.displayhook.prompt_count + 1
  446. for n in range(1, pc):
  447. key = '_i'+repr(n)
  448. user_ns.pop(key,None)
  449. user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
  450. hm = ip.history_manager
  451. # don't delete these, as %save and %macro depending on the
  452. # length of these lists to be preserved
  453. hm.input_hist_parsed[:] = [''] * pc
  454. hm.input_hist_raw[:] = [''] * pc
  455. # hm has internal machinery for _i,_ii,_iii, clear it out
  456. hm._i = hm._ii = hm._iii = hm._i00 = u''
  457. elif target == 'array':
  458. # Support cleaning up numpy arrays
  459. try:
  460. from numpy import ndarray
  461. # This must be done with items and not iteritems because
  462. # we're going to modify the dict in-place.
  463. for x,val in list(user_ns.items()):
  464. if isinstance(val,ndarray):
  465. del user_ns[x]
  466. except ImportError:
  467. print("reset array only works if Numpy is available.")
  468. elif target == 'dhist':
  469. print("Flushing directory history")
  470. del user_ns['_dh'][:]
  471. else:
  472. print("Don't know how to reset ", end=' ')
  473. print(target + ", please run `%reset?` for details")
  474. gc.collect()
  475. @line_magic
  476. def reset_selective(self, parameter_s=''):
  477. """Resets the namespace by removing names defined by the user.
  478. Input/Output history are left around in case you need them.
  479. %reset_selective [-f] regex
  480. No action is taken if regex is not included
  481. Options
  482. -f : force reset without asking for confirmation.
  483. See Also
  484. --------
  485. reset : invoked as ``%reset``
  486. Examples
  487. --------
  488. We first fully reset the namespace so your output looks identical to
  489. this example for pedagogical reasons; in practice you do not need a
  490. full reset::
  491. In [1]: %reset -f
  492. Now, with a clean namespace we can make a few variables and use
  493. ``%reset_selective`` to only delete names that match our regexp::
  494. In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
  495. In [3]: who_ls
  496. Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
  497. In [4]: %reset_selective -f b[2-3]m
  498. In [5]: who_ls
  499. Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
  500. In [6]: %reset_selective -f d
  501. In [7]: who_ls
  502. Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
  503. In [8]: %reset_selective -f c
  504. In [9]: who_ls
  505. Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
  506. In [10]: %reset_selective -f b
  507. In [11]: who_ls
  508. Out[11]: ['a']
  509. Notes
  510. -----
  511. Calling this magic from clients that do not implement standard input,
  512. such as the ipython notebook interface, will reset the namespace
  513. without confirmation.
  514. """
  515. opts, regex = self.parse_options(parameter_s,'f')
  516. if 'f' in opts:
  517. ans = True
  518. else:
  519. try:
  520. ans = self.shell.ask_yes_no(
  521. "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
  522. default='n')
  523. except StdinNotImplementedError:
  524. ans = True
  525. if not ans:
  526. print('Nothing done.')
  527. return
  528. user_ns = self.shell.user_ns
  529. if not regex:
  530. print('No regex pattern specified. Nothing done.')
  531. return
  532. else:
  533. try:
  534. m = re.compile(regex)
  535. except TypeError:
  536. raise TypeError('regex must be a string or compiled pattern')
  537. for i in self.who_ls():
  538. if m.search(i):
  539. del(user_ns[i])
  540. @line_magic
  541. def xdel(self, parameter_s=''):
  542. """Delete a variable, trying to clear it from anywhere that
  543. IPython's machinery has references to it. By default, this uses
  544. the identity of the named object in the user namespace to remove
  545. references held under other names. The object is also removed
  546. from the output history.
  547. Options
  548. -n : Delete the specified name from all namespaces, without
  549. checking their identity.
  550. """
  551. opts, varname = self.parse_options(parameter_s,'n')
  552. try:
  553. self.shell.del_var(varname, ('n' in opts))
  554. except (NameError, ValueError) as e:
  555. print(type(e).__name__ +": "+ str(e))