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.

reflect.py 19KB

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