reflect.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. # -*- test-case-name: twisted.test.test_reflect -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Standardized versions of various cool and/or strange things that you can do
  6. with Python's reflection capabilities.
  7. """
  8. from __future__ import division, absolute_import, print_function
  9. import sys
  10. import types
  11. import os
  12. import pickle
  13. import weakref
  14. import re
  15. import traceback
  16. from collections import deque
  17. RegexType = type(re.compile(""))
  18. from twisted.python.compat import reraise, nativeString, NativeStringIO
  19. from twisted.python.compat import _PY3
  20. from twisted.python import compat
  21. from twisted.python.deprecate import _fullyQualifiedName as fullyQualifiedName
  22. from twisted.python._oldstyle import _oldStyle
  23. def prefixedMethodNames(classObj, prefix):
  24. """
  25. Given a class object C{classObj}, returns a list of method names that match
  26. the string C{prefix}.
  27. @param classObj: A class object from which to collect method names.
  28. @param prefix: A native string giving a prefix. Each method with a name
  29. which begins with this prefix will be returned.
  30. @type prefix: L{str}
  31. @return: A list of the names of matching methods of C{classObj} (and base
  32. classes of C{classObj}).
  33. @rtype: L{list} of L{str}
  34. """
  35. dct = {}
  36. addMethodNamesToDict(classObj, dct, prefix)
  37. return list(dct.keys())
  38. def addMethodNamesToDict(classObj, dict, prefix, baseClass=None):
  39. """
  40. This goes through C{classObj} (and its bases) and puts method names
  41. starting with 'prefix' in 'dict' with a value of 1. if baseClass isn't
  42. None, methods will only be added if classObj is-a baseClass
  43. If the class in question has the methods 'prefix_methodname' and
  44. 'prefix_methodname2', the resulting dict should look something like:
  45. {"methodname": 1, "methodname2": 1}.
  46. @param classObj: A class object from which to collect method names.
  47. @param dict: A L{dict} which will be updated with the results of the
  48. accumulation. Items are added to this dictionary, with method names as
  49. keys and C{1} as values.
  50. @type dict: L{dict}
  51. @param prefix: A native string giving a prefix. Each method of C{classObj}
  52. (and base classes of C{classObj}) with a name which begins with this
  53. prefix will be returned.
  54. @type prefix: L{str}
  55. @param baseClass: A class object at which to stop searching upwards for new
  56. methods. To collect all method names, do not pass a value for this
  57. parameter.
  58. @return: L{None}
  59. """
  60. for base in classObj.__bases__:
  61. addMethodNamesToDict(base, dict, prefix, baseClass)
  62. if baseClass is None or baseClass in classObj.__bases__:
  63. for name, method in classObj.__dict__.items():
  64. optName = name[len(prefix):]
  65. if ((type(method) is types.FunctionType)
  66. and (name[:len(prefix)] == prefix)
  67. and (len(optName))):
  68. dict[optName] = 1
  69. def prefixedMethods(obj, prefix=''):
  70. """
  71. Given an object C{obj}, returns a list of method objects that match the
  72. string C{prefix}.
  73. @param obj: An arbitrary object from which to collect methods.
  74. @param prefix: A native string giving a prefix. Each method of C{obj} with
  75. a name which begins with this prefix will be returned.
  76. @type prefix: L{str}
  77. @return: A list of the matching method objects.
  78. @rtype: L{list}
  79. """
  80. dct = {}
  81. accumulateMethods(obj, dct, prefix)
  82. return list(dct.values())
  83. def accumulateMethods(obj, dict, prefix='', curClass=None):
  84. """
  85. Given an object C{obj}, add all methods that begin with C{prefix}.
  86. @param obj: An arbitrary object to collect methods from.
  87. @param dict: A L{dict} which will be updated with the results of the
  88. accumulation. Items are added to this dictionary, with method names as
  89. keys and corresponding instance method objects as values.
  90. @type dict: L{dict}
  91. @param prefix: A native string giving a prefix. Each method of C{obj} with
  92. a name which begins with this prefix will be returned.
  93. @type prefix: L{str}
  94. @param curClass: The class in the inheritance hierarchy at which to start
  95. collecting methods. Collection proceeds up. To collect all methods
  96. from C{obj}, do not pass a value for this parameter.
  97. @return: L{None}
  98. """
  99. if not curClass:
  100. curClass = obj.__class__
  101. for base in curClass.__bases__:
  102. accumulateMethods(obj, dict, prefix, base)
  103. for name, method in curClass.__dict__.items():
  104. optName = name[len(prefix):]
  105. if ((type(method) is types.FunctionType)
  106. and (name[:len(prefix)] == prefix)
  107. and (len(optName))):
  108. dict[optName] = getattr(obj, name)
  109. def namedModule(name):
  110. """
  111. Return a module given its name.
  112. """
  113. topLevel = __import__(name)
  114. packages = name.split(".")[1:]
  115. m = topLevel
  116. for p in packages:
  117. m = getattr(m, p)
  118. return m
  119. def namedObject(name):
  120. """
  121. Get a fully named module-global object.
  122. """
  123. classSplit = name.split('.')
  124. module = namedModule('.'.join(classSplit[:-1]))
  125. return getattr(module, classSplit[-1])
  126. namedClass = namedObject # backwards compat
  127. def requireModule(name, default=None):
  128. """
  129. Try to import a module given its name, returning C{default} value if
  130. C{ImportError} is raised during import.
  131. @param name: Module name as it would have been passed to C{import}.
  132. @type name: C{str}.
  133. @param default: Value returned in case C{ImportError} is raised while
  134. importing the module.
  135. @return: Module or default value.
  136. """
  137. try:
  138. return namedModule(name)
  139. except ImportError:
  140. return default
  141. class _NoModuleFound(Exception):
  142. """
  143. No module was found because none exists.
  144. """
  145. class InvalidName(ValueError):
  146. """
  147. The given name is not a dot-separated list of Python objects.
  148. """
  149. class ModuleNotFound(InvalidName):
  150. """
  151. The module associated with the given name doesn't exist and it can't be
  152. imported.
  153. """
  154. class ObjectNotFound(InvalidName):
  155. """
  156. The object associated with the given name doesn't exist and it can't be
  157. imported.
  158. """
  159. def _importAndCheckStack(importName):
  160. """
  161. Import the given name as a module, then walk the stack to determine whether
  162. the failure was the module not existing, or some code in the module (for
  163. example a dependent import) failing. This can be helpful to determine
  164. whether any actual application code was run. For example, to distiguish
  165. administrative error (entering the wrong module name), from programmer
  166. error (writing buggy code in a module that fails to import).
  167. @param importName: The name of the module to import.
  168. @type importName: C{str}
  169. @raise Exception: if something bad happens. This can be any type of
  170. exception, since nobody knows what loading some arbitrary code might
  171. do.
  172. @raise _NoModuleFound: if no module was found.
  173. """
  174. try:
  175. return __import__(importName)
  176. except ImportError:
  177. excType, excValue, excTraceback = sys.exc_info()
  178. while excTraceback:
  179. execName = excTraceback.tb_frame.f_globals["__name__"]
  180. # in Python 2 execName is None when an ImportError is encountered,
  181. # where in Python 3 execName is equal to the importName.
  182. if execName is None or execName == importName:
  183. reraise(excValue, excTraceback)
  184. excTraceback = excTraceback.tb_next
  185. raise _NoModuleFound()
  186. def namedAny(name):
  187. """
  188. Retrieve a Python object by its fully qualified name from the global Python
  189. module namespace. The first part of the name, that describes a module,
  190. will be discovered and imported. Each subsequent part of the name is
  191. treated as the name of an attribute of the object specified by all of the
  192. name which came before it. For example, the fully-qualified name of this
  193. object is 'twisted.python.reflect.namedAny'.
  194. @type name: L{str}
  195. @param name: The name of the object to return.
  196. @raise InvalidName: If the name is an empty string, starts or ends with
  197. a '.', or is otherwise syntactically incorrect.
  198. @raise ModuleNotFound: If the name is syntactically correct but the
  199. module it specifies cannot be imported because it does not appear to
  200. exist.
  201. @raise ObjectNotFound: If the name is syntactically correct, includes at
  202. least one '.', but the module it specifies cannot be imported because
  203. it does not appear to exist.
  204. @raise AttributeError: If an attribute of an object along the way cannot be
  205. accessed, or a module along the way is not found.
  206. @return: the Python object identified by 'name'.
  207. """
  208. if not name:
  209. raise InvalidName('Empty module name')
  210. names = name.split('.')
  211. # if the name starts or ends with a '.' or contains '..', the __import__
  212. # will raise an 'Empty module name' error. This will provide a better error
  213. # message.
  214. if '' in names:
  215. raise InvalidName(
  216. "name must be a string giving a '.'-separated list of Python "
  217. "identifiers, not %r" % (name,))
  218. topLevelPackage = None
  219. moduleNames = names[:]
  220. while not topLevelPackage:
  221. if moduleNames:
  222. trialname = '.'.join(moduleNames)
  223. try:
  224. topLevelPackage = _importAndCheckStack(trialname)
  225. except _NoModuleFound:
  226. moduleNames.pop()
  227. else:
  228. if len(names) == 1:
  229. raise ModuleNotFound("No module named %r" % (name,))
  230. else:
  231. raise ObjectNotFound('%r does not name an object' % (name,))
  232. obj = topLevelPackage
  233. for n in names[1:]:
  234. obj = getattr(obj, n)
  235. return obj
  236. def filenameToModuleName(fn):
  237. """
  238. Convert a name in the filesystem to the name of the Python module it is.
  239. This is aggressive about getting a module name back from a file; it will
  240. always return a string. Aggressive means 'sometimes wrong'; it won't look
  241. at the Python path or try to do any error checking: don't use this method
  242. unless you already know that the filename you're talking about is a Python
  243. module.
  244. @param fn: A filesystem path to a module or package; C{bytes} on Python 2,
  245. C{bytes} or C{unicode} on Python 3.
  246. @return: A hopefully importable module name.
  247. @rtype: C{str}
  248. """
  249. if isinstance(fn, bytes):
  250. initPy = b"__init__.py"
  251. else:
  252. initPy = "__init__.py"
  253. fullName = os.path.abspath(fn)
  254. base = os.path.basename(fn)
  255. if not base:
  256. # this happens when fn ends with a path separator, just skit it
  257. base = os.path.basename(fn[:-1])
  258. modName = nativeString(os.path.splitext(base)[0])
  259. while 1:
  260. fullName = os.path.dirname(fullName)
  261. if os.path.exists(os.path.join(fullName, initPy)):
  262. modName = "%s.%s" % (
  263. nativeString(os.path.basename(fullName)),
  264. nativeString(modName))
  265. else:
  266. break
  267. return modName
  268. def qual(clazz):
  269. """
  270. Return full import path of a class.
  271. """
  272. return clazz.__module__ + '.' + clazz.__name__
  273. def _determineClass(x):
  274. try:
  275. return x.__class__
  276. except:
  277. return type(x)
  278. def _determineClassName(x):
  279. c = _determineClass(x)
  280. try:
  281. return c.__name__
  282. except:
  283. try:
  284. return str(c)
  285. except:
  286. return '<BROKEN CLASS AT 0x%x>' % id(c)
  287. def _safeFormat(formatter, o):
  288. """
  289. Helper function for L{safe_repr} and L{safe_str}.
  290. Called when C{repr} or C{str} fail. Returns a string containing info about
  291. C{o} and the latest exception.
  292. @param formatter: C{str} or C{repr}.
  293. @type formatter: C{type}
  294. @param o: Any object.
  295. @rtype: C{str}
  296. @return: A string containing information about C{o} and the raised
  297. exception.
  298. """
  299. io = NativeStringIO()
  300. traceback.print_exc(file=io)
  301. className = _determineClassName(o)
  302. tbValue = io.getvalue()
  303. return "<%s instance at 0x%x with %s error:\n %s>" % (
  304. className, id(o), formatter.__name__, tbValue)
  305. def safe_repr(o):
  306. """
  307. Returns a string representation of an object, or a string containing a
  308. traceback, if that object's __repr__ raised an exception.
  309. @param o: Any object.
  310. @rtype: C{str}
  311. """
  312. try:
  313. return repr(o)
  314. except:
  315. return _safeFormat(repr, o)
  316. def safe_str(o):
  317. """
  318. Returns a string representation of an object, or a string containing a
  319. traceback, if that object's __str__ raised an exception.
  320. @param o: Any object.
  321. @rtype: C{str}
  322. """
  323. if _PY3 and isinstance(o, bytes):
  324. # If o is bytes and seems to holds a utf-8 encoded string,
  325. # convert it to str.
  326. try:
  327. return o.decode('utf-8')
  328. except:
  329. pass
  330. try:
  331. return str(o)
  332. except:
  333. return _safeFormat(str, o)
  334. @_oldStyle
  335. class QueueMethod:
  336. """
  337. I represent a method that doesn't exist yet.
  338. """
  339. def __init__(self, name, calls):
  340. self.name = name
  341. self.calls = calls
  342. def __call__(self, *args):
  343. self.calls.append((self.name, args))
  344. def fullFuncName(func):
  345. qualName = (str(pickle.whichmodule(func, func.__name__)) + '.' + func.__name__)
  346. if namedObject(qualName) is not func:
  347. raise Exception("Couldn't find %s as %s." % (func, qualName))
  348. return qualName
  349. def getClass(obj):
  350. """
  351. Return the class or type of object 'obj'.
  352. Returns sensible result for oldstyle and newstyle instances and types.
  353. """
  354. if hasattr(obj, '__class__'):
  355. return obj.__class__
  356. else:
  357. return type(obj)
  358. def accumulateClassDict(classObj, attr, adict, baseClass=None):
  359. """
  360. Accumulate all attributes of a given name in a class hierarchy into a single dictionary.
  361. Assuming all class attributes of this name are dictionaries.
  362. If any of the dictionaries being accumulated have the same key, the
  363. one highest in the class hierarchy wins.
  364. (XXX: If \"highest\" means \"closest to the starting class\".)
  365. Ex::
  366. class Soy:
  367. properties = {\"taste\": \"bland\"}
  368. class Plant:
  369. properties = {\"colour\": \"green\"}
  370. class Seaweed(Plant):
  371. pass
  372. class Lunch(Soy, Seaweed):
  373. properties = {\"vegan\": 1 }
  374. dct = {}
  375. accumulateClassDict(Lunch, \"properties\", dct)
  376. print(dct)
  377. {\"taste\": \"bland\", \"colour\": \"green\", \"vegan\": 1}
  378. """
  379. for base in classObj.__bases__:
  380. accumulateClassDict(base, attr, adict)
  381. if baseClass is None or baseClass in classObj.__bases__:
  382. adict.update(classObj.__dict__.get(attr, {}))
  383. def accumulateClassList(classObj, attr, listObj, baseClass=None):
  384. """
  385. Accumulate all attributes of a given name in a class hierarchy into a single list.
  386. Assuming all class attributes of this name are lists.
  387. """
  388. for base in classObj.__bases__:
  389. accumulateClassList(base, attr, listObj)
  390. if baseClass is None or baseClass in classObj.__bases__:
  391. listObj.extend(classObj.__dict__.get(attr, []))
  392. def isSame(a, b):
  393. return (a is b)
  394. def isLike(a, b):
  395. return (a == b)
  396. def modgrep(goal):
  397. return objgrep(sys.modules, goal, isLike, 'sys.modules')
  398. def isOfType(start, goal):
  399. return ((type(start) is goal) or
  400. (isinstance(start, compat.InstanceType) and
  401. start.__class__ is goal))
  402. def findInstances(start, t):
  403. return objgrep(start, t, isOfType)
  404. if not _PY3:
  405. # The function objgrep() currently doesn't work on Python 3 due to some
  406. # edge cases, as described in #6986.
  407. # twisted.python.reflect is quite important and objgrep is not used in
  408. # Twisted itself, so in #5929, we decided to port everything but objgrep()
  409. # and to finish the porting in #6986
  410. def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None,
  411. showUnknowns=0, maxDepth=None):
  412. """
  413. An insanely CPU-intensive process for finding stuff.
  414. """
  415. if paths is None:
  416. paths = []
  417. if seen is None:
  418. seen = {}
  419. if eq(start, goal):
  420. paths.append(path)
  421. if id(start) in seen:
  422. if seen[id(start)] is start:
  423. return
  424. if maxDepth is not None:
  425. if maxDepth == 0:
  426. return
  427. maxDepth -= 1
  428. seen[id(start)] = start
  429. # Make an alias for those arguments which are passed recursively to
  430. # objgrep for container objects.
  431. args = (paths, seen, showUnknowns, maxDepth)
  432. if isinstance(start, dict):
  433. for k, v in start.items():
  434. objgrep(k, goal, eq, path+'{'+repr(v)+'}', *args)
  435. objgrep(v, goal, eq, path+'['+repr(k)+']', *args)
  436. elif isinstance(start, (list, tuple, deque)):
  437. for idx, _elem in enumerate(start):
  438. objgrep(start[idx], goal, eq, path+'['+str(idx)+']', *args)
  439. elif isinstance(start, types.MethodType):
  440. objgrep(start.__self__, goal, eq, path+'.__self__', *args)
  441. objgrep(start.__func__, goal, eq, path+'.__func__', *args)
  442. objgrep(start.__self__.__class__, goal, eq,
  443. path+'.__self__.__class__', *args)
  444. elif hasattr(start, '__dict__'):
  445. for k, v in start.__dict__.items():
  446. objgrep(v, goal, eq, path+'.'+k, *args)
  447. if isinstance(start, compat.InstanceType):
  448. objgrep(start.__class__, goal, eq, path+'.__class__', *args)
  449. elif isinstance(start, weakref.ReferenceType):
  450. objgrep(start(), goal, eq, path+'()', *args)
  451. elif (isinstance(start, (compat.StringType,
  452. int, types.FunctionType,
  453. types.BuiltinMethodType, RegexType, float,
  454. type(None), compat.FileType)) or
  455. type(start).__name__ in ('wrapper_descriptor',
  456. 'method_descriptor', 'member_descriptor',
  457. 'getset_descriptor')):
  458. pass
  459. elif showUnknowns:
  460. print('unknown type', type(start), start)
  461. return paths
  462. __all__ = [
  463. 'InvalidName', 'ModuleNotFound', 'ObjectNotFound',
  464. 'QueueMethod',
  465. 'namedModule', 'namedObject', 'namedClass', 'namedAny', 'requireModule',
  466. 'safe_repr', 'safe_str', 'prefixedMethodNames', 'addMethodNamesToDict',
  467. 'prefixedMethods', 'accumulateMethods', 'fullFuncName', 'qual', 'getClass',
  468. 'accumulateClassDict', 'accumulateClassList', 'isSame', 'isLike',
  469. 'modgrep', 'isOfType', 'findInstances', 'objgrep', 'filenameToModuleName',
  470. 'fullyQualifiedName']
  471. if _PY3:
  472. # This is to be removed when fixing #6986
  473. __all__.remove('objgrep')