You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1011 lines
44 KiB

4 years ago
  1. #!/usr/bin/env python
  2. #
  3. # Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
  4. # Copyright (c) 2008-2016 California Institute of Technology.
  5. # Copyright (c) 2016-2018 The Uncertainty Quantification Foundation.
  6. # License: 3-clause BSD. The full license text is available at:
  7. # - https://github.com/uqfoundation/dill/blob/master/LICENSE
  8. #
  9. # inspired by inspect.py from Python-2.7.6
  10. # inspect.py author: 'Ka-Ping Yee <ping@lfw.org>'
  11. # inspect.py merged into original dill.source by Mike McKerns 4/13/14
  12. """
  13. Extensions to python's 'inspect' module, which can be used
  14. to retrieve information from live python objects. The methods
  15. defined in this module are augmented to facilitate access to
  16. source code of interactively defined functions and classes,
  17. as well as provide access to source code for objects defined
  18. in a file.
  19. """
  20. __all__ = ['findsource', 'getsourcelines', 'getsource', 'indent', 'outdent', \
  21. '_wrap', 'dumpsource', 'getname', '_namespace', 'getimport', \
  22. '_importable', 'importable','isdynamic', 'isfrommain']
  23. import re
  24. import linecache
  25. from tokenize import TokenError
  26. from inspect import ismodule, isclass, ismethod, isfunction, istraceback
  27. from inspect import isframe, iscode, getfile, getmodule, getsourcefile
  28. from inspect import getblock, indentsize, isbuiltin
  29. from ._dill import PY3
  30. def isfrommain(obj):
  31. "check if object was built in __main__"
  32. module = getmodule(obj)
  33. if module and module.__name__ == '__main__':
  34. return True
  35. return False
  36. def isdynamic(obj):
  37. "check if object was built in the interpreter"
  38. try: file = getfile(obj)
  39. except TypeError: file = None
  40. if file == '<stdin>' and isfrommain(obj):
  41. return True
  42. return False
  43. def _matchlambda(func, line):
  44. """check if lambda object 'func' matches raw line of code 'line'"""
  45. from .detect import code as getcode
  46. from .detect import freevars, globalvars, varnames
  47. dummy = lambda : '__this_is_a_big_dummy_function__'
  48. # process the line (removing leading whitespace, etc)
  49. lhs,rhs = line.split('lambda ',1)[-1].split(":", 1) #FIXME: if !1 inputs
  50. try: #FIXME: unsafe
  51. _ = eval("lambda %s : %s" % (lhs,rhs), globals(),locals())
  52. except: _ = dummy
  53. # get code objects, for comparison
  54. _, code = getcode(_).co_code, getcode(func).co_code
  55. # check if func is in closure
  56. _f = [line.count(i) for i in freevars(func).keys()]
  57. if not _f: # not in closure
  58. # check if code matches
  59. if _ == code: return True
  60. return False
  61. # weak check on freevars
  62. if not all(_f): return False #XXX: VERY WEAK
  63. # weak check on varnames and globalvars
  64. _f = varnames(func)
  65. _f = [line.count(i) for i in _f[0]+_f[1]]
  66. if _f and not all(_f): return False #XXX: VERY WEAK
  67. _f = [line.count(i) for i in globalvars(func).keys()]
  68. if _f and not all(_f): return False #XXX: VERY WEAK
  69. # check if func is a double lambda
  70. if (line.count('lambda ') > 1) and (lhs in freevars(func).keys()):
  71. _lhs,_rhs = rhs.split('lambda ',1)[-1].split(":",1) #FIXME: if !1 inputs
  72. try: #FIXME: unsafe
  73. _f = eval("lambda %s : %s" % (_lhs,_rhs), globals(),locals())
  74. except: _f = dummy
  75. # get code objects, for comparison
  76. _, code = getcode(_f).co_code, getcode(func).co_code
  77. if len(_) != len(code): return False
  78. #NOTE: should be same code same order, but except for 't' and '\x88'
  79. _ = set((i,j) for (i,j) in zip(_,code) if i != j)
  80. if len(_) != 1: return False #('t','\x88')
  81. return True
  82. # check indentsize
  83. if not indentsize(line): return False #FIXME: is this a good check???
  84. # check if code 'pattern' matches
  85. #XXX: or pattern match against dis.dis(code)? (or use uncompyle2?)
  86. _ = _.split(_[0]) # 't' #XXX: remove matching values if starts the same?
  87. _f = code.split(code[0]) # '\x88'
  88. #NOTE: should be same code different order, with different first element
  89. _ = dict(re.match('([\W\D\S])(.*)', _[i]).groups() for i in range(1,len(_)))
  90. _f = dict(re.match('([\W\D\S])(.*)', _f[i]).groups() for i in range(1,len(_f)))
  91. if (_.keys() == _f.keys()) and (sorted(_.values()) == sorted(_f.values())):
  92. return True
  93. return False
  94. def findsource(object):
  95. """Return the entire source file and starting line number for an object.
  96. For interactively-defined objects, the 'file' is the interpreter's history.
  97. The argument may be a module, class, method, function, traceback, frame,
  98. or code object. The source code is returned as a list of all the lines
  99. in the file and the line number indexes a line in that list. An IOError
  100. is raised if the source code cannot be retrieved, while a TypeError is
  101. raised for objects where the source code is unavailable (e.g. builtins)."""
  102. module = getmodule(object)
  103. try: file = getfile(module)
  104. except TypeError: file = None
  105. # use readline when working in interpreter (i.e. __main__ and not file)
  106. if module and module.__name__ == '__main__' and not file:
  107. import readline
  108. lbuf = readline.get_current_history_length()
  109. lines = [readline.get_history_item(i)+'\n' for i in range(1,lbuf)]
  110. else:
  111. try: # special handling for class instances
  112. if not isclass(object) and isclass(type(object)): # __class__
  113. file = getfile(module)
  114. sourcefile = getsourcefile(module)
  115. else: # builtins fail with a TypeError
  116. file = getfile(object)
  117. sourcefile = getsourcefile(object)
  118. except (TypeError, AttributeError): # fail with better error
  119. file = getfile(object)
  120. sourcefile = getsourcefile(object)
  121. if not sourcefile and file[:1] + file[-1:] != '<>':
  122. raise IOError('source code not available')
  123. file = sourcefile if sourcefile else file
  124. module = getmodule(object, file)
  125. if module:
  126. lines = linecache.getlines(file, module.__dict__)
  127. else:
  128. lines = linecache.getlines(file)
  129. if not lines:
  130. raise IOError('could not get source code')
  131. #FIXME: all below may fail if exec used (i.e. exec('f = lambda x:x') )
  132. if ismodule(object):
  133. return lines, 0
  134. name = pat1 = obj = ''
  135. pat2 = r'^(\s*@)'
  136. # pat1b = r'^(\s*%s\W*=)' % name #FIXME: finds 'f = decorate(f)', not exec
  137. if ismethod(object):
  138. name = object.__name__
  139. if name == '<lambda>': pat1 = r'(.*(?<!\w)lambda(:|\s))'
  140. else: pat1 = r'^(\s*def\s)'
  141. if PY3: object = object.__func__
  142. else: object = object.im_func
  143. if isfunction(object):
  144. name = object.__name__
  145. if name == '<lambda>':
  146. pat1 = r'(.*(?<!\w)lambda(:|\s))'
  147. obj = object #XXX: better a copy?
  148. else: pat1 = r'^(\s*def\s)'
  149. if PY3: object = object.__code__
  150. else: object = object.func_code
  151. if istraceback(object):
  152. object = object.tb_frame
  153. if isframe(object):
  154. object = object.f_code
  155. if iscode(object):
  156. if not hasattr(object, 'co_firstlineno'):
  157. raise IOError('could not find function definition')
  158. stdin = object.co_filename == '<stdin>'
  159. if stdin:
  160. lnum = len(lines) - 1 # can't get lnum easily, so leverage pat
  161. if not pat1: pat1 = r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)'
  162. else:
  163. lnum = object.co_firstlineno - 1
  164. pat1 = r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)'
  165. pat1 = re.compile(pat1); pat2 = re.compile(pat2)
  166. #XXX: candidate_lnum = [n for n in range(lnum) if pat1.match(lines[n])]
  167. while lnum > 0: #XXX: won't find decorators in <stdin> ?
  168. line = lines[lnum]
  169. if pat1.match(line):
  170. if not stdin: break # co_firstlineno does the job
  171. if name == '<lambda>': # hackery needed to confirm a match
  172. if _matchlambda(obj, line): break
  173. else: # not a lambda, just look for the name
  174. if name in line: # need to check for decorator...
  175. hats = 0
  176. for _lnum in range(lnum-1,-1,-1):
  177. if pat2.match(lines[_lnum]): hats += 1
  178. else: break
  179. lnum = lnum - hats
  180. break
  181. lnum = lnum - 1
  182. return lines, lnum
  183. try: # turn instances into classes
  184. if not isclass(object) and isclass(type(object)): # __class__
  185. object = object.__class__ #XXX: sometimes type(class) is better?
  186. #XXX: we don't find how the instance was built
  187. except AttributeError: pass
  188. if isclass(object):
  189. name = object.__name__
  190. pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
  191. # make some effort to find the best matching class definition:
  192. # use the one with the least indentation, which is the one
  193. # that's most probably not inside a function definition.
  194. candidates = []
  195. for i in range(len(lines)-1,-1,-1):
  196. match = pat.match(lines[i])
  197. if match:
  198. # if it's at toplevel, it's already the best one
  199. if lines[i][0] == 'c':
  200. return lines, i
  201. # else add whitespace to candidate list
  202. candidates.append((match.group(1), i))
  203. if candidates:
  204. # this will sort by whitespace, and by line number,
  205. # less whitespace first #XXX: should sort high lnum before low
  206. candidates.sort()
  207. return lines, candidates[0][1]
  208. else:
  209. raise IOError('could not find class definition')
  210. raise IOError('could not find code object')
  211. def getblocks(object, lstrip=False, enclosing=False, locate=False):
  212. """Return a list of source lines and starting line number for an object.
  213. Interactively-defined objects refer to lines in the interpreter's history.
  214. If enclosing=True, then also return any enclosing code.
  215. If lstrip=True, ensure there is no indentation in the first line of code.
  216. If locate=True, then also return the line number for the block of code.
  217. DEPRECATED: use 'getsourcelines' instead
  218. """
  219. lines, lnum = findsource(object)
  220. if ismodule(object):
  221. if lstrip: lines = _outdent(lines)
  222. return ([lines], [0]) if locate is True else [lines]
  223. #XXX: 'enclosing' means: closures only? or classes and files?
  224. indent = indentsize(lines[lnum])
  225. block = getblock(lines[lnum:]) #XXX: catch any TokenError here?
  226. if not enclosing or not indent:
  227. if lstrip: block = _outdent(block)
  228. return ([block], [lnum]) if locate is True else [block]
  229. pat1 = r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))'; pat1 = re.compile(pat1)
  230. pat2 = r'^(\s*@)'; pat2 = re.compile(pat2)
  231. #pat3 = r'^(\s*class\s)'; pat3 = re.compile(pat3) #XXX: enclosing class?
  232. #FIXME: bound methods need enclosing class (and then instantiation)
  233. # *or* somehow apply a partial using the instance
  234. skip = 0
  235. line = 0
  236. blocks = []; _lnum = []
  237. target = ''.join(block)
  238. while line <= lnum: #XXX: repeat lnum? or until line < lnum?
  239. # see if starts with ('def','lambda') and contains our target block
  240. if pat1.match(lines[line]):
  241. if not skip:
  242. try: code = getblock(lines[line:])
  243. except TokenError: code = [lines[line]]
  244. if indentsize(lines[line]) > indent: #XXX: should be >= ?
  245. line += len(code) - skip
  246. elif target in ''.join(code):
  247. blocks.append(code) # save code block as the potential winner
  248. _lnum.append(line - skip) # save the line number for the match
  249. line += len(code) - skip
  250. else:
  251. line += 1
  252. skip = 0
  253. # find skip: the number of consecutive decorators
  254. elif pat2.match(lines[line]):
  255. try: code = getblock(lines[line:])
  256. except TokenError: code = [lines[line]]
  257. skip = 1
  258. for _line in code[1:]: # skip lines that are decorators
  259. if not pat2.match(_line): break
  260. skip += 1
  261. line += skip
  262. # no match: reset skip and go to the next line
  263. else:
  264. line +=1
  265. skip = 0
  266. if not blocks:
  267. blocks = [block]
  268. _lnum = [lnum]
  269. if lstrip: blocks = [_outdent(block) for block in blocks]
  270. # return last match
  271. return (blocks, _lnum) if locate is True else blocks
  272. def getsourcelines(object, lstrip=False, enclosing=False):
  273. """Return a list of source lines and starting line number for an object.
  274. Interactively-defined objects refer to lines in the interpreter's history.
  275. The argument may be a module, class, method, function, traceback, frame,
  276. or code object. The source code is returned as a list of the lines
  277. corresponding to the object and the line number indicates where in the
  278. original source file the first line of code was found. An IOError is
  279. raised if the source code cannot be retrieved, while a TypeError is
  280. raised for objects where the source code is unavailable (e.g. builtins).
  281. If lstrip=True, ensure there is no indentation in the first line of code.
  282. If enclosing=True, then also return any enclosing code."""
  283. code, n = getblocks(object, lstrip=lstrip, enclosing=enclosing, locate=True)
  284. return code[-1], n[-1]
  285. #NOTE: broke backward compatibility 4/16/14 (was lstrip=True, force=True)
  286. def getsource(object, alias='', lstrip=False, enclosing=False, \
  287. force=False, builtin=False):
  288. """Return the text of the source code for an object. The source code for
  289. interactively-defined objects are extracted from the interpreter's history.
  290. The argument may be a module, class, method, function, traceback, frame,
  291. or code object. The source code is returned as a single string. An
  292. IOError is raised if the source code cannot be retrieved, while a
  293. TypeError is raised for objects where the source code is unavailable
  294. (e.g. builtins).
  295. If alias is provided, then add a line of code that renames the object.
  296. If lstrip=True, ensure there is no indentation in the first line of code.
  297. If enclosing=True, then also return any enclosing code.
  298. If force=True, catch (TypeError,IOError) and try to use import hooks.
  299. If builtin=True, force an import for any builtins
  300. """
  301. # hascode denotes a callable
  302. hascode = _hascode(object)
  303. # is a class instance type (and not in builtins)
  304. instance = _isinstance(object)
  305. # get source lines; if fail, try to 'force' an import
  306. try: # fails for builtins, and other assorted object types
  307. lines, lnum = getsourcelines(object, enclosing=enclosing)
  308. except (TypeError, IOError): # failed to get source, resort to import hooks
  309. if not force: # don't try to get types that findsource can't get
  310. raise
  311. if not getmodule(object): # get things like 'None' and '1'
  312. if not instance: return getimport(object, alias, builtin=builtin)
  313. # special handling (numpy arrays, ...)
  314. _import = getimport(object, builtin=builtin)
  315. name = getname(object, force=True)
  316. _alias = "%s = " % alias if alias else ""
  317. if alias == name: _alias = ""
  318. return _import+_alias+"%s\n" % name
  319. else: #FIXME: could use a good bit of cleanup, since using getimport...
  320. if not instance: return getimport(object, alias, builtin=builtin)
  321. # now we are dealing with an instance...
  322. name = object.__class__.__name__
  323. module = object.__module__
  324. if module in ['builtins','__builtin__']:
  325. return getimport(object, alias, builtin=builtin)
  326. else: #FIXME: leverage getimport? use 'from module import name'?
  327. lines, lnum = ["%s = __import__('%s', fromlist=['%s']).%s\n" % (name,module,name,name)], 0
  328. obj = eval(lines[0].lstrip(name + ' = '))
  329. lines, lnum = getsourcelines(obj, enclosing=enclosing)
  330. # strip leading indent (helps ensure can be imported)
  331. if lstrip or alias:
  332. lines = _outdent(lines)
  333. # instantiate, if there's a nice repr #XXX: BAD IDEA???
  334. if instance: #and force: #XXX: move into findsource or getsourcelines ?
  335. if '(' in repr(object): lines.append('%r\n' % object)
  336. #else: #XXX: better to somehow to leverage __reduce__ ?
  337. # reconstructor,args = object.__reduce__()
  338. # _ = reconstructor(*args)
  339. else: # fall back to serialization #XXX: bad idea?
  340. #XXX: better not duplicate work? #XXX: better new/enclose=True?
  341. lines = dumpsource(object, alias='', new=force, enclose=False)
  342. lines, lnum = [line+'\n' for line in lines.split('\n')][:-1], 0
  343. #else: object.__code__ # raise AttributeError
  344. # add an alias to the source code
  345. if alias:
  346. if hascode:
  347. skip = 0
  348. for line in lines: # skip lines that are decorators
  349. if not line.startswith('@'): break
  350. skip += 1
  351. #XXX: use regex from findsource / getsourcelines ?
  352. if lines[skip].lstrip().startswith('def '): # we have a function
  353. if alias != object.__name__:
  354. lines.append('\n%s = %s\n' % (alias, object.__name__))
  355. elif 'lambda ' in lines[skip]: # we have a lambda
  356. if alias != lines[skip].split('=')[0].strip():
  357. lines[skip] = '%s = %s' % (alias, lines[skip])
  358. else: # ...try to use the object's name
  359. if alias != object.__name__:
  360. lines.append('\n%s = %s\n' % (alias, object.__name__))
  361. else: # class or class instance
  362. if instance:
  363. if alias != lines[-1].split('=')[0].strip():
  364. lines[-1] = ('%s = ' % alias) + lines[-1]
  365. else:
  366. name = getname(object, force=True) or object.__name__
  367. if alias != name:
  368. lines.append('\n%s = %s\n' % (alias, name))
  369. return ''.join(lines)
  370. def _hascode(object):
  371. '''True if object has an attribute that stores it's __code__'''
  372. return getattr(object,'__code__',None) or getattr(object,'func_code',None)
  373. def _isinstance(object):
  374. '''True if object is a class instance type (and is not a builtin)'''
  375. if _hascode(object) or isclass(object) or ismodule(object):
  376. return False
  377. if istraceback(object) or isframe(object) or iscode(object):
  378. return False
  379. # special handling (numpy arrays, ...)
  380. if not getmodule(object) and getmodule(type(object)).__name__ in ['numpy']:
  381. return True
  382. # # check if is instance of a builtin
  383. # if not getmodule(object) and getmodule(type(object)).__name__ in ['__builtin__','builtins']:
  384. # return False
  385. _types = ('<class ',"<type 'instance'>")
  386. if not repr(type(object)).startswith(_types): #FIXME: weak hack
  387. return False
  388. if not getmodule(object) or object.__module__ in ['builtins','__builtin__'] or getname(object, force=True) in ['array']:
  389. return False
  390. return True # by process of elimination... it's what we want
  391. def _intypes(object):
  392. '''check if object is in the 'types' module'''
  393. import types
  394. # allow user to pass in object or object.__name__
  395. if type(object) is not type(''):
  396. object = getname(object, force=True)
  397. if object == 'ellipsis': object = 'EllipsisType'
  398. return True if hasattr(types, object) else False
  399. def _isstring(object): #XXX: isstringlike better?
  400. '''check if object is a string-like type'''
  401. if PY3: return isinstance(object, (str, bytes))
  402. return isinstance(object, basestring)
  403. def indent(code, spaces=4):
  404. '''indent a block of code with whitespace (default is 4 spaces)'''
  405. indent = indentsize(code)
  406. if type(spaces) is int: spaces = ' '*spaces
  407. # if '\t' is provided, will indent with a tab
  408. nspaces = indentsize(spaces)
  409. # blank lines (etc) need to be ignored
  410. lines = code.split('\n')
  411. ## stq = "'''"; dtq = '"""'
  412. ## in_stq = in_dtq = False
  413. for i in range(len(lines)):
  414. #FIXME: works... but shouldn't indent 2nd+ lines of multiline doc
  415. _indent = indentsize(lines[i])
  416. if indent > _indent: continue
  417. lines[i] = spaces+lines[i]
  418. ## #FIXME: may fail when stq and dtq in same line (depends on ordering)
  419. ## nstq, ndtq = lines[i].count(stq), lines[i].count(dtq)
  420. ## if not in_dtq and not in_stq:
  421. ## lines[i] = spaces+lines[i] # we indent
  422. ## # entering a comment block
  423. ## if nstq%2: in_stq = not in_stq
  424. ## if ndtq%2: in_dtq = not in_dtq
  425. ## # leaving a comment block
  426. ## elif in_dtq and ndtq%2: in_dtq = not in_dtq
  427. ## elif in_stq and nstq%2: in_stq = not in_stq
  428. ## else: pass
  429. if lines[-1].strip() == '': lines[-1] = ''
  430. return '\n'.join(lines)
  431. def _outdent(lines, spaces=None, all=True):
  432. '''outdent lines of code, accounting for docs and line continuations'''
  433. indent = indentsize(lines[0])
  434. if spaces is None or spaces > indent or spaces < 0: spaces = indent
  435. for i in range(len(lines) if all else 1):
  436. #FIXME: works... but shouldn't outdent 2nd+ lines of multiline doc
  437. _indent = indentsize(lines[i])
  438. if spaces > _indent: _spaces = _indent
  439. else: _spaces = spaces
  440. lines[i] = lines[i][_spaces:]
  441. return lines
  442. def outdent(code, spaces=None, all=True):
  443. '''outdent a block of code (default is to strip all leading whitespace)'''
  444. indent = indentsize(code)
  445. if spaces is None or spaces > indent or spaces < 0: spaces = indent
  446. #XXX: will this delete '\n' in some cases?
  447. if not all: return code[spaces:]
  448. return '\n'.join(_outdent(code.split('\n'), spaces=spaces, all=all))
  449. #XXX: not sure what the point of _wrap is...
  450. #exec_ = lambda s, *a: eval(compile(s, '<string>', 'exec'), *a)
  451. __globals__ = globals()
  452. __locals__ = locals()
  453. wrap2 = '''
  454. def _wrap(f):
  455. """ encapsulate a function and it's __import__ """
  456. def func(*args, **kwds):
  457. try:
  458. # _ = eval(getsource(f, force=True)) #XXX: safer but less robust
  459. exec getimportable(f, alias='_') in %s, %s
  460. except:
  461. raise ImportError('cannot import name ' + f.__name__)
  462. return _(*args, **kwds)
  463. func.__name__ = f.__name__
  464. func.__doc__ = f.__doc__
  465. return func
  466. ''' % ('__globals__', '__locals__')
  467. wrap3 = '''
  468. def _wrap(f):
  469. """ encapsulate a function and it's __import__ """
  470. def func(*args, **kwds):
  471. try:
  472. # _ = eval(getsource(f, force=True)) #XXX: safer but less robust
  473. exec(getimportable(f, alias='_'), %s, %s)
  474. except:
  475. raise ImportError('cannot import name ' + f.__name__)
  476. return _(*args, **kwds)
  477. func.__name__ = f.__name__
  478. func.__doc__ = f.__doc__
  479. return func
  480. ''' % ('__globals__', '__locals__')
  481. if PY3:
  482. exec(wrap3)
  483. else:
  484. exec(wrap2)
  485. del wrap2, wrap3
  486. def _enclose(object, alias=''): #FIXME: needs alias to hold returned object
  487. """create a function enclosure around the source of some object"""
  488. #XXX: dummy and stub should append a random string
  489. dummy = '__this_is_a_big_dummy_enclosing_function__'
  490. stub = '__this_is_a_stub_variable__'
  491. code = 'def %s():\n' % dummy
  492. code += indent(getsource(object, alias=stub, lstrip=True, force=True))
  493. code += indent('return %s\n' % stub)
  494. if alias: code += '%s = ' % alias
  495. code += '%s(); del %s\n' % (dummy, dummy)
  496. #code += "globals().pop('%s',lambda :None)()\n" % dummy
  497. return code
  498. def dumpsource(object, alias='', new=False, enclose=True):
  499. """'dump to source', where the code includes a pickled object.
  500. If new=True and object is a class instance, then create a new
  501. instance using the unpacked class source code. If enclose, then
  502. create the object inside a function enclosure (thus minimizing
  503. any global namespace pollution).
  504. """
  505. from dill import dumps
  506. pik = repr(dumps(object))
  507. code = 'import dill\n'
  508. if enclose:
  509. stub = '__this_is_a_stub_variable__' #XXX: *must* be same _enclose.stub
  510. pre = '%s = ' % stub
  511. new = False #FIXME: new=True doesn't work with enclose=True
  512. else:
  513. stub = alias
  514. pre = '%s = ' % stub if alias else alias
  515. # if a 'new' instance is not needed, then just dump and load
  516. if not new or not _isinstance(object):
  517. code += pre + 'dill.loads(%s)\n' % pik
  518. else: #XXX: other cases where source code is needed???
  519. code += getsource(object.__class__, alias='', lstrip=True, force=True)
  520. mod = repr(object.__module__) # should have a module (no builtins here)
  521. if PY3:
  522. code += pre + 'dill.loads(%s.replace(b%s,bytes(__name__,"UTF-8")))\n' % (pik,mod)
  523. else:
  524. code += pre + 'dill.loads(%s.replace(%s,__name__))\n' % (pik,mod)
  525. #code += 'del %s' % object.__class__.__name__ #NOTE: kills any existing!
  526. if enclose:
  527. # generation of the 'enclosure'
  528. dummy = '__this_is_a_big_dummy_object__'
  529. dummy = _enclose(dummy, alias=alias)
  530. # hack to replace the 'dummy' with the 'real' code
  531. dummy = dummy.split('\n')
  532. code = dummy[0]+'\n' + indent(code) + '\n'.join(dummy[-3:])
  533. return code #XXX: better 'dumpsourcelines', returning list of lines?
  534. def getname(obj, force=False, fqn=False): #XXX: throw(?) to raise error on fail?
  535. """get the name of the object. for lambdas, get the name of the pointer """
  536. if fqn: return '.'.join(_namespace(obj))
  537. module = getmodule(obj)
  538. if not module: # things like "None" and "1"
  539. if not force: return None
  540. return repr(obj)
  541. try:
  542. #XXX: 'wrong' for decorators and curried functions ?
  543. # if obj.func_closure: ...use logic from getimportable, etc ?
  544. name = obj.__name__
  545. if name == '<lambda>':
  546. return getsource(obj).split('=',1)[0].strip()
  547. # handle some special cases
  548. if module.__name__ in ['builtins','__builtin__']:
  549. if name == 'ellipsis': name = 'EllipsisType'
  550. return name
  551. except AttributeError: #XXX: better to just throw AttributeError ?
  552. if not force: return None
  553. name = repr(obj)
  554. if name.startswith('<'): # or name.split('('):
  555. return None
  556. return name
  557. def _namespace(obj):
  558. """_namespace(obj); return namespace hierarchy (as a list of names)
  559. for the given object. For an instance, find the class hierarchy.
  560. For example:
  561. >>> from functools import partial
  562. >>> p = partial(int, base=2)
  563. >>> _namespace(p)
  564. [\'functools\', \'partial\']
  565. """
  566. # mostly for functions and modules and such
  567. #FIXME: 'wrong' for decorators and curried functions
  568. try: #XXX: needs some work and testing on different types
  569. module = qual = str(getmodule(obj)).split()[1].strip('"').strip("'")
  570. qual = qual.split('.')
  571. if ismodule(obj):
  572. return qual
  573. # get name of a lambda, function, etc
  574. name = getname(obj) or obj.__name__ # failing, raise AttributeError
  575. # check special cases (NoneType, ...)
  576. if module in ['builtins','__builtin__']: # BuiltinFunctionType
  577. if _intypes(name): return ['types'] + [name]
  578. return qual + [name] #XXX: can be wrong for some aliased objects
  579. except: pass
  580. # special case: numpy.inf and numpy.nan (we don't want them as floats)
  581. if str(obj) in ['inf','nan','Inf','NaN']: # is more, but are they needed?
  582. return ['numpy'] + [str(obj)]
  583. # mostly for classes and class instances and such
  584. module = getattr(obj.__class__, '__module__', None)
  585. qual = str(obj.__class__)
  586. try: qual = qual[qual.index("'")+1:-2]
  587. except ValueError: pass # str(obj.__class__) made the 'try' unnecessary
  588. qual = qual.split(".")
  589. if module in ['builtins','__builtin__']:
  590. # check special cases (NoneType, Ellipsis, ...)
  591. if qual[-1] == 'ellipsis': qual[-1] = 'EllipsisType'
  592. if _intypes(qual[-1]): module = 'types' #XXX: BuiltinFunctionType
  593. qual = [module] + qual
  594. return qual
  595. #NOTE: 05/25/14 broke backward compatability: added 'alias' as 3rd argument
  596. def _getimport(head, tail, alias='', verify=True, builtin=False):
  597. """helper to build a likely import string from head and tail of namespace.
  598. ('head','tail') are used in the following context: "from head import tail"
  599. If verify=True, then test the import string before returning it.
  600. If builtin=True, then force an import for builtins where possible.
  601. If alias is provided, then rename the object on import.
  602. """
  603. # special handling for a few common types
  604. if tail in ['Ellipsis', 'NotImplemented'] and head in ['types']:
  605. head = len.__module__
  606. elif tail in ['None'] and head in ['types']:
  607. _alias = '%s = ' % alias if alias else ''
  608. if alias == tail: _alias = ''
  609. return _alias+'%s\n' % tail
  610. # we don't need to import from builtins, so return ''
  611. # elif tail in ['NoneType','int','float','long','complex']: return '' #XXX: ?
  612. if head in ['builtins','__builtin__']:
  613. # special cases (NoneType, Ellipsis, ...) #XXX: BuiltinFunctionType
  614. if tail == 'ellipsis': tail = 'EllipsisType'
  615. if _intypes(tail): head = 'types'
  616. elif not builtin:
  617. _alias = '%s = ' % alias if alias else ''
  618. if alias == tail: _alias = ''
  619. return _alias+'%s\n' % tail
  620. else: pass # handle builtins below
  621. # get likely import string
  622. if not head: _str = "import %s" % tail
  623. else: _str = "from %s import %s" % (head, tail)
  624. _alias = " as %s\n" % alias if alias else "\n"
  625. if alias == tail: _alias = "\n"
  626. _str += _alias
  627. # FIXME: fails on most decorators, currying, and such...
  628. # (could look for magic __wrapped__ or __func__ attr)
  629. # (could fix in 'namespace' to check obj for closure)
  630. if verify and not head.startswith('dill.'):# weird behavior for dill
  631. #print(_str)
  632. try: exec(_str) #XXX: check if == obj? (name collision)
  633. except ImportError: #XXX: better top-down or bottom-up recursion?
  634. _head = head.rsplit(".",1)[0] #(or get all, then compare == obj?)
  635. if not _head: raise
  636. if _head != head:
  637. _str = _getimport(_head, tail, alias, verify)
  638. return _str
  639. #XXX: rename builtin to force? vice versa? verify to force? (as in getsource)
  640. #NOTE: 05/25/14 broke backward compatability: added 'alias' as 2nd argument
  641. def getimport(obj, alias='', verify=True, builtin=False, enclosing=False):
  642. """get the likely import string for the given object
  643. obj is the object to inspect
  644. If verify=True, then test the import string before returning it.
  645. If builtin=True, then force an import for builtins where possible.
  646. If enclosing=True, get the import for the outermost enclosing callable.
  647. If alias is provided, then rename the object on import.
  648. """
  649. if enclosing:
  650. from .detect import outermost
  651. _obj = outermost(obj)
  652. obj = _obj if _obj else obj
  653. # get the namespace
  654. qual = _namespace(obj)
  655. head = '.'.join(qual[:-1])
  656. tail = qual[-1]
  657. # for named things... with a nice repr #XXX: move into _namespace?
  658. try: # look for '<...>' and be mindful it might be in lists, dicts, etc...
  659. name = repr(obj).split('<',1)[1].split('>',1)[1]
  660. name = None # we have a 'object'-style repr
  661. except: # it's probably something 'importable'
  662. if head in ['builtins','__builtin__']:
  663. name = repr(obj) #XXX: catch [1,2], (1,2), set([1,2])... others?
  664. else:
  665. name = repr(obj).split('(')[0]
  666. #if not repr(obj).startswith('<'): name = repr(obj).split('(')[0]
  667. #else: name = None
  668. if name: # try using name instead of tail
  669. try: return _getimport(head, name, alias, verify, builtin)
  670. except ImportError: pass
  671. except SyntaxError:
  672. if head in ['builtins','__builtin__']:
  673. _alias = '%s = ' % alias if alias else ''
  674. if alias == name: _alias = ''
  675. return _alias+'%s\n' % name
  676. else: pass
  677. try:
  678. #if type(obj) is type(abs): _builtin = builtin # BuiltinFunctionType
  679. #else: _builtin = False
  680. return _getimport(head, tail, alias, verify, builtin)
  681. except ImportError:
  682. raise # could do some checking against obj
  683. except SyntaxError:
  684. if head in ['builtins','__builtin__']:
  685. _alias = '%s = ' % alias if alias else ''
  686. if alias == tail: _alias = ''
  687. return _alias+'%s\n' % tail
  688. raise # could do some checking against obj
  689. def _importable(obj, alias='', source=None, enclosing=False, force=True, \
  690. builtin=True, lstrip=True):
  691. """get an import string (or the source code) for the given object
  692. This function will attempt to discover the name of the object, or the repr
  693. of the object, or the source code for the object. To attempt to force
  694. discovery of the source code, use source=True, to attempt to force the
  695. use of an import, use source=False; otherwise an import will be sought
  696. for objects not defined in __main__. The intent is to build a string
  697. that can be imported from a python file. obj is the object to inspect.
  698. If alias is provided, then rename the object with the given alias.
  699. If source=True, use these options:
  700. If enclosing=True, then also return any enclosing code.
  701. If force=True, catch (TypeError,IOError) and try to use import hooks.
  702. If lstrip=True, ensure there is no indentation in the first line of code.
  703. If source=False, use these options:
  704. If enclosing=True, get the import for the outermost enclosing callable.
  705. If force=True, then don't test the import string before returning it.
  706. If builtin=True, then force an import for builtins where possible.
  707. """
  708. if source is None:
  709. source = True if isfrommain(obj) else False
  710. if source: # first try to get the source
  711. try:
  712. return getsource(obj, alias, enclosing=enclosing, \
  713. force=force, lstrip=lstrip, builtin=builtin)
  714. except: pass
  715. try:
  716. if not _isinstance(obj):
  717. return getimport(obj, alias, enclosing=enclosing, \
  718. verify=(not force), builtin=builtin)
  719. # first 'get the import', then 'get the instance'
  720. _import = getimport(obj, enclosing=enclosing, \
  721. verify=(not force), builtin=builtin)
  722. name = getname(obj, force=True)
  723. if not name:
  724. raise AttributeError("object has no atribute '__name__'")
  725. _alias = "%s = " % alias if alias else ""
  726. if alias == name: _alias = ""
  727. return _import+_alias+"%s\n" % name
  728. except: pass
  729. if not source: # try getsource, only if it hasn't been tried yet
  730. try:
  731. return getsource(obj, alias, enclosing=enclosing, \
  732. force=force, lstrip=lstrip, builtin=builtin)
  733. except: pass
  734. # get the name (of functions, lambdas, and classes)
  735. # or hope that obj can be built from the __repr__
  736. #XXX: what to do about class instances and such?
  737. obj = getname(obj, force=force)
  738. # we either have __repr__ or __name__ (or None)
  739. if not obj or obj.startswith('<'):
  740. raise AttributeError("object has no atribute '__name__'")
  741. _alias = '%s = ' % alias if alias else ''
  742. if alias == obj: _alias = ''
  743. return _alias+'%s\n' % obj
  744. #XXX: possible failsafe... (for example, for instances when source=False)
  745. # "import dill; result = dill.loads(<pickled_object>); # repr(<object>)"
  746. def _closuredimport(func, alias='', builtin=False):
  747. """get import for closured objects; return a dict of 'name' and 'import'"""
  748. import re
  749. from .detect import freevars, outermost
  750. free_vars = freevars(func)
  751. func_vars = {}
  752. # split into 'funcs' and 'non-funcs'
  753. for name,obj in list(free_vars.items()):
  754. if not isfunction(obj): continue
  755. # get import for 'funcs'
  756. fobj = free_vars.pop(name)
  757. src = getsource(fobj)
  758. if src.lstrip().startswith('@'): # we have a decorator
  759. src = getimport(fobj, alias=alias, builtin=builtin)
  760. else: # we have to "hack" a bit... and maybe be lucky
  761. encl = outermost(func)
  762. # pattern: 'func = enclosing(fobj'
  763. pat = '.*[\w\s]=\s*'+getname(encl)+'\('+getname(fobj)
  764. mod = getname(getmodule(encl))
  765. #HACK: get file containing 'outer' function; is func there?
  766. lines,_ = findsource(encl)
  767. candidate = [line for line in lines if getname(encl) in line and \
  768. re.match(pat, line)]
  769. if not candidate:
  770. mod = getname(getmodule(fobj))
  771. #HACK: get file containing 'inner' function; is func there?
  772. lines,_ = findsource(fobj)
  773. candidate = [line for line in lines \
  774. if getname(fobj) in line and re.match(pat, line)]
  775. if not len(candidate): raise TypeError('import could not be found')
  776. candidate = candidate[-1]
  777. name = candidate.split('=',1)[0].split()[-1].strip()
  778. src = _getimport(mod, name, alias=alias, builtin=builtin)
  779. func_vars[name] = src
  780. if not func_vars:
  781. name = outermost(func)
  782. mod = getname(getmodule(name))
  783. if not mod or name is func: # then it can be handled by getimport
  784. name = getname(func, force=True) #XXX: better key?
  785. src = getimport(func, alias=alias, builtin=builtin)
  786. else:
  787. lines,_ = findsource(name)
  788. # pattern: 'func = enclosing('
  789. candidate = [line for line in lines if getname(name) in line and \
  790. re.match('.*[\w\s]=\s*'+getname(name)+'\(', line)]
  791. if not len(candidate): raise TypeError('import could not be found')
  792. candidate = candidate[-1]
  793. name = candidate.split('=',1)[0].split()[-1].strip()
  794. src = _getimport(mod, name, alias=alias, builtin=builtin)
  795. func_vars[name] = src
  796. return func_vars
  797. #XXX: should be able to use __qualname__
  798. def _closuredsource(func, alias=''):
  799. """get source code for closured objects; return a dict of 'name'
  800. and 'code blocks'"""
  801. #FIXME: this entire function is a messy messy HACK
  802. # - pollutes global namespace
  803. # - fails if name of freevars are reused
  804. # - can unnecessarily duplicate function code
  805. from .detect import freevars
  806. free_vars = freevars(func)
  807. func_vars = {}
  808. # split into 'funcs' and 'non-funcs'
  809. for name,obj in list(free_vars.items()):
  810. if not isfunction(obj):
  811. # get source for 'non-funcs'
  812. free_vars[name] = getsource(obj, force=True, alias=name)
  813. continue
  814. # get source for 'funcs'
  815. fobj = free_vars.pop(name)
  816. src = getsource(fobj, alias) # DO NOT include dependencies
  817. # if source doesn't start with '@', use name as the alias
  818. if not src.lstrip().startswith('@'): #FIXME: 'enclose' in dummy;
  819. src = importable(fobj,alias=name)# wrong ref 'name'
  820. org = getsource(func, alias, enclosing=False, lstrip=True)
  821. src = (src, org) # undecorated first, then target
  822. else: #NOTE: reproduces the code!
  823. org = getsource(func, enclosing=True, lstrip=False)
  824. src = importable(fobj, alias, source=True) # include dependencies
  825. src = (org, src) # target first, then decorated
  826. func_vars[name] = src
  827. src = ''.join(free_vars.values())
  828. if not func_vars: #FIXME: 'enclose' in dummy; wrong ref 'name'
  829. org = getsource(func, alias, force=True, enclosing=False, lstrip=True)
  830. src = (src, org) # variables first, then target
  831. else:
  832. src = (src, None) # just variables (better '' instead of None?)
  833. func_vars[None] = src
  834. # FIXME: remove duplicates (however, order is important...)
  835. return func_vars
  836. def importable(obj, alias='', source=None, builtin=True):
  837. """get an importable string (i.e. source code or the import string)
  838. for the given object, including any required objects from the enclosing
  839. and global scope
  840. This function will attempt to discover the name of the object, or the repr
  841. of the object, or the source code for the object. To attempt to force
  842. discovery of the source code, use source=True, to attempt to force the
  843. use of an import, use source=False; otherwise an import will be sought
  844. for objects not defined in __main__. The intent is to build a string
  845. that can be imported from a python file.
  846. obj is the object to inspect. If alias is provided, then rename the
  847. object with the given alias. If builtin=True, then force an import for
  848. builtins where possible.
  849. """
  850. #NOTE: we always 'force', and 'lstrip' as necessary
  851. #NOTE: for 'enclosing', use importable(outermost(obj))
  852. if source is None:
  853. source = True if isfrommain(obj) else False
  854. elif builtin and isbuiltin(obj):
  855. source = False
  856. tried_source = tried_import = False
  857. while True:
  858. if not source: # we want an import
  859. try:
  860. if _isinstance(obj): # for instances, punt to _importable
  861. return _importable(obj, alias, source=False, builtin=builtin)
  862. src = _closuredimport(obj, alias=alias, builtin=builtin)
  863. if len(src) == 0:
  864. raise NotImplementedError('not implemented')
  865. if len(src) > 1:
  866. raise NotImplementedError('not implemented')
  867. return list(src.values())[0]
  868. except:
  869. if tried_source: raise
  870. tried_import = True
  871. # we want the source
  872. try:
  873. src = _closuredsource(obj, alias=alias)
  874. if len(src) == 0:
  875. raise NotImplementedError('not implemented')
  876. # groan... an inline code stitcher
  877. def _code_stitcher(block):
  878. "stitch together the strings in tuple 'block'"
  879. if block[0] and block[-1]: block = '\n'.join(block)
  880. elif block[0]: block = block[0]
  881. elif block[-1]: block = block[-1]
  882. else: block = ''
  883. return block
  884. # get free_vars first
  885. _src = _code_stitcher(src.pop(None))
  886. _src = [_src] if _src else []
  887. # get func_vars
  888. for xxx in src.values():
  889. xxx = _code_stitcher(xxx)
  890. if xxx: _src.append(xxx)
  891. # make a single source string
  892. if not len(_src):
  893. src = ''
  894. elif len(_src) == 1:
  895. src = _src[0]
  896. else:
  897. src = '\n'.join(_src)
  898. # get source code of objects referred to by obj in global scope
  899. from .detect import globalvars
  900. obj = globalvars(obj) #XXX: don't worry about alias? recurse? etc?
  901. obj = list(getsource(_obj,name,force=True) for (name,_obj) in obj.items() if not isbuiltin(_obj))
  902. obj = '\n'.join(obj) if obj else ''
  903. # combine all referred-to source (global then enclosing)
  904. if not obj: return src
  905. if not src: return obj
  906. return obj + src
  907. except:
  908. if tried_import: raise
  909. tried_source = True
  910. source = not source
  911. # should never get here
  912. return
  913. # backward compatability
  914. def getimportable(obj, alias='', byname=True, explicit=False):
  915. return importable(obj,alias,source=(not byname),builtin=explicit)
  916. #return outdent(_importable(obj,alias,source=(not byname),builtin=explicit))
  917. def likely_import(obj, passive=False, explicit=False):
  918. return getimport(obj, verify=(not passive), builtin=explicit)
  919. def _likely_import(first, last, passive=False, explicit=True):
  920. return _getimport(first, last, verify=(not passive), builtin=explicit)
  921. _get_name = getname
  922. getblocks_from_history = getblocks
  923. # EOF