Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

modules.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. # -*- test-case-name: twisted.test.test_modules -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module aims to provide a unified, object-oriented view of Python's
  6. runtime hierarchy.
  7. Python is a very dynamic language with wide variety of introspection utilities.
  8. However, these utilities can be hard to use, because there is no consistent
  9. API. The introspection API in python is made up of attributes (__name__,
  10. __module__, func_name, etc) on instances, modules, classes and functions which
  11. vary between those four types, utility modules such as 'inspect' which provide
  12. some functionality, the 'imp' module, the "compiler" module, the semantics of
  13. PEP 302 support, and setuptools, among other things.
  14. At the top, you have "PythonPath", an abstract representation of sys.path which
  15. includes methods to locate top-level modules, with or without loading them.
  16. The top-level exposed functions in this module for accessing the system path
  17. are "walkModules", "iterModules", and "getModule".
  18. From most to least specific, here are the objects provided::
  19. PythonPath # sys.path
  20. |
  21. v
  22. PathEntry # one entry on sys.path: an importer
  23. |
  24. v
  25. PythonModule # a module or package that can be loaded
  26. |
  27. v
  28. PythonAttribute # an attribute of a module (function or class)
  29. |
  30. v
  31. PythonAttribute # an attribute of a function or class
  32. |
  33. v
  34. ...
  35. Here's an example of idiomatic usage: this is what you would do to list all of
  36. the modules outside the standard library's python-files directory::
  37. import os
  38. stdlibdir = os.path.dirname(os.__file__)
  39. from twisted.python.modules import iterModules
  40. for modinfo in iterModules():
  41. if (modinfo.pathEntry.filePath.path != stdlibdir
  42. and not modinfo.isPackage()):
  43. print('unpackaged: %s: %s' % (
  44. modinfo.name, modinfo.filePath.path))
  45. @var theSystemPath: The very top of the Python object space.
  46. @type theSystemPath: L{PythonPath}
  47. """
  48. import inspect
  49. import sys
  50. import warnings
  51. import zipimport
  52. # let's try to keep path imports to a minimum...
  53. from os.path import dirname, split as splitpath
  54. from zope.interface import Interface, implementer
  55. from twisted.python.compat import nativeString
  56. from twisted.python.components import registerAdapter
  57. from twisted.python.filepath import FilePath, UnlistableError
  58. from twisted.python.reflect import namedAny
  59. from twisted.python.zippath import ZipArchive
  60. _nothing = object()
  61. PYTHON_EXTENSIONS = [".py"]
  62. OPTIMIZED_MODE = __doc__ is None
  63. if OPTIMIZED_MODE:
  64. PYTHON_EXTENSIONS.append(".pyo")
  65. else:
  66. PYTHON_EXTENSIONS.append(".pyc")
  67. def _isPythonIdentifier(string):
  68. """
  69. cheezy fake test for proper identifier-ness.
  70. @param string: a L{str} which might or might not be a valid python
  71. identifier.
  72. @return: True or False
  73. """
  74. textString = nativeString(string)
  75. return " " not in textString and "." not in textString and "-" not in textString
  76. def _isPackagePath(fpath):
  77. # Determine if a FilePath-like object is a Python package. TODO: deal with
  78. # __init__module.(so|dll|pyd)?
  79. extless = fpath.splitext()[0]
  80. basend = splitpath(extless)[1]
  81. return basend == "__init__"
  82. class _ModuleIteratorHelper:
  83. """
  84. This mixin provides common behavior between python module and path entries,
  85. since the mechanism for searching sys.path and __path__ attributes is
  86. remarkably similar.
  87. """
  88. def iterModules(self):
  89. """
  90. Loop over the modules present below this entry or package on PYTHONPATH.
  91. For modules which are not packages, this will yield nothing.
  92. For packages and path entries, this will only yield modules one level
  93. down; i.e. if there is a package a.b.c, iterModules on a will only
  94. return a.b. If you want to descend deeply, use walkModules.
  95. @return: a generator which yields PythonModule instances that describe
  96. modules which can be, or have been, imported.
  97. """
  98. yielded = {}
  99. if not self.filePath.exists():
  100. return
  101. for placeToLook in self._packagePaths():
  102. try:
  103. children = sorted(placeToLook.children())
  104. except UnlistableError:
  105. continue
  106. for potentialTopLevel in children:
  107. ext = potentialTopLevel.splitext()[1]
  108. potentialBasename = potentialTopLevel.basename()[: -len(ext)]
  109. if ext in PYTHON_EXTENSIONS:
  110. # TODO: this should be a little choosier about which path entry
  111. # it selects first, and it should do all the .so checking and
  112. # crud
  113. if not _isPythonIdentifier(potentialBasename):
  114. continue
  115. modname = self._subModuleName(potentialBasename)
  116. if modname.split(".")[-1] == "__init__":
  117. # This marks the directory as a package so it can't be
  118. # a module.
  119. continue
  120. if modname not in yielded:
  121. yielded[modname] = True
  122. pm = PythonModule(modname, potentialTopLevel, self._getEntry())
  123. assert pm != self
  124. yield pm
  125. else:
  126. if (
  127. ext
  128. or not _isPythonIdentifier(potentialBasename)
  129. or not potentialTopLevel.isdir()
  130. ):
  131. continue
  132. modname = self._subModuleName(potentialTopLevel.basename())
  133. for ext in PYTHON_EXTENSIONS:
  134. initpy = potentialTopLevel.child("__init__" + ext)
  135. if initpy.exists() and modname not in yielded:
  136. yielded[modname] = True
  137. pm = PythonModule(modname, initpy, self._getEntry())
  138. assert pm != self
  139. yield pm
  140. break
  141. def walkModules(self, importPackages=False):
  142. """
  143. Similar to L{iterModules}, this yields self, and then every module in my
  144. package or entry, and every submodule in each package or entry.
  145. In other words, this is deep, and L{iterModules} is shallow.
  146. """
  147. yield self
  148. for package in self.iterModules():
  149. yield from package.walkModules(importPackages=importPackages)
  150. def _subModuleName(self, mn):
  151. """
  152. This is a hook to provide packages with the ability to specify their names
  153. as a prefix to submodules here.
  154. """
  155. return mn
  156. def _packagePaths(self):
  157. """
  158. Implement in subclasses to specify where to look for modules.
  159. @return: iterable of FilePath-like objects.
  160. """
  161. raise NotImplementedError()
  162. def _getEntry(self):
  163. """
  164. Implement in subclasses to specify what path entry submodules will come
  165. from.
  166. @return: a PathEntry instance.
  167. """
  168. raise NotImplementedError()
  169. def __getitem__(self, modname):
  170. """
  171. Retrieve a module from below this path or package.
  172. @param modname: a str naming a module to be loaded. For entries, this
  173. is a top-level, undotted package name, and for packages it is the name
  174. of the module without the package prefix. For example, if you have a
  175. PythonModule representing the 'twisted' package, you could use::
  176. twistedPackageObj['python']['modules']
  177. to retrieve this module.
  178. @raise KeyError: if the module is not found.
  179. @return: a PythonModule.
  180. """
  181. for module in self.iterModules():
  182. if module.name == self._subModuleName(modname):
  183. return module
  184. raise KeyError(modname)
  185. def __iter__(self):
  186. """
  187. Implemented to raise NotImplementedError for clarity, so that attempting to
  188. loop over this object won't call __getitem__.
  189. Note: in the future there might be some sensible default for iteration,
  190. like 'walkEverything', so this is deliberately untested and undefined
  191. behavior.
  192. """
  193. raise NotImplementedError()
  194. class PythonAttribute:
  195. """
  196. I represent a function, class, or other object that is present.
  197. @ivar name: the fully-qualified python name of this attribute.
  198. @ivar onObject: a reference to a PythonModule or other PythonAttribute that
  199. is this attribute's logical parent.
  200. @ivar name: the fully qualified python name of the attribute represented by
  201. this class.
  202. """
  203. def __init__(self, name, onObject, loaded, pythonValue):
  204. """
  205. Create a PythonAttribute. This is a private constructor. Do not construct
  206. me directly, use PythonModule.iterAttributes.
  207. @param name: the FQPN
  208. @param onObject: see ivar
  209. @param loaded: always True, for now
  210. @param pythonValue: the value of the attribute we're pointing to.
  211. """
  212. self.name: str = name
  213. self.onObject = onObject
  214. self._loaded = loaded
  215. self.pythonValue = pythonValue
  216. def __repr__(self) -> str:
  217. return f"PythonAttribute<{self.name!r}>"
  218. def isLoaded(self):
  219. """
  220. Return a boolean describing whether the attribute this describes has
  221. actually been loaded into memory by importing its module.
  222. Note: this currently always returns true; there is no Python parser
  223. support in this module yet.
  224. """
  225. return self._loaded
  226. def load(self, default=_nothing):
  227. """
  228. Load the value associated with this attribute.
  229. @return: an arbitrary Python object, or 'default' if there is an error
  230. loading it.
  231. """
  232. return self.pythonValue
  233. def iterAttributes(self):
  234. for name, val in inspect.getmembers(self.load()):
  235. yield PythonAttribute(self.name + "." + name, self, True, val)
  236. class PythonModule(_ModuleIteratorHelper):
  237. """
  238. Representation of a module which could be imported from sys.path.
  239. @ivar name: the fully qualified python name of this module.
  240. @ivar filePath: a FilePath-like object which points to the location of this
  241. module.
  242. @ivar pathEntry: a L{PathEntry} instance which this module was located
  243. from.
  244. """
  245. def __init__(self, name, filePath, pathEntry):
  246. """
  247. Create a PythonModule. Do not construct this directly, instead inspect a
  248. PythonPath or other PythonModule instances.
  249. @param name: see ivar
  250. @param filePath: see ivar
  251. @param pathEntry: see ivar
  252. """
  253. _name = nativeString(name)
  254. assert not _name.endswith(".__init__")
  255. self.name: str = _name
  256. self.filePath = filePath
  257. self.parentPath = filePath.parent()
  258. self.pathEntry = pathEntry
  259. def _getEntry(self):
  260. return self.pathEntry
  261. def __repr__(self) -> str:
  262. """
  263. Return a string representation including the module name.
  264. """
  265. return f"PythonModule<{self.name!r}>"
  266. def isLoaded(self):
  267. """
  268. Determine if the module is loaded into sys.modules.
  269. @return: a boolean: true if loaded, false if not.
  270. """
  271. return self.pathEntry.pythonPath.moduleDict.get(self.name) is not None
  272. def iterAttributes(self):
  273. """
  274. List all the attributes defined in this module.
  275. Note: Future work is planned here to make it possible to list python
  276. attributes on a module without loading the module by inspecting ASTs or
  277. bytecode, but currently any iteration of PythonModule objects insists
  278. they must be loaded, and will use inspect.getmodule.
  279. @raise NotImplementedError: if this module is not loaded.
  280. @return: a generator yielding PythonAttribute instances describing the
  281. attributes of this module.
  282. """
  283. if not self.isLoaded():
  284. raise NotImplementedError(
  285. "You can't load attributes from non-loaded modules yet."
  286. )
  287. for name, val in inspect.getmembers(self.load()):
  288. yield PythonAttribute(self.name + "." + name, self, True, val)
  289. def isPackage(self):
  290. """
  291. Returns true if this module is also a package, and might yield something
  292. from iterModules.
  293. """
  294. return _isPackagePath(self.filePath)
  295. def load(self, default=_nothing):
  296. """
  297. Load this module.
  298. @param default: if specified, the value to return in case of an error.
  299. @return: a genuine python module.
  300. @raise Exception: Importing modules is a risky business;
  301. the erorrs of any code run at module scope may be raised from here, as
  302. well as ImportError if something bizarre happened to the system path
  303. between the discovery of this PythonModule object and the attempt to
  304. import it. If you specify a default, the error will be swallowed
  305. entirely, and not logged.
  306. @rtype: types.ModuleType.
  307. """
  308. try:
  309. return self.pathEntry.pythonPath.moduleLoader(self.name)
  310. except BaseException: # this needs more thought...
  311. if default is not _nothing:
  312. return default
  313. raise
  314. def __eq__(self, other: object) -> bool:
  315. """
  316. PythonModules with the same name are equal.
  317. """
  318. if isinstance(other, PythonModule):
  319. return other.name == self.name
  320. return NotImplemented
  321. def walkModules(self, importPackages=False):
  322. if importPackages and self.isPackage():
  323. self.load()
  324. return super().walkModules(importPackages=importPackages)
  325. def _subModuleName(self, mn):
  326. """
  327. submodules of this module are prefixed with our name.
  328. """
  329. return self.name + "." + mn
  330. def _packagePaths(self):
  331. """
  332. Yield a sequence of FilePath-like objects which represent path segments.
  333. """
  334. if not self.isPackage():
  335. return
  336. if self.isLoaded():
  337. load = self.load()
  338. if hasattr(load, "__path__"):
  339. for fn in load.__path__:
  340. if fn == self.parentPath.path:
  341. # this should _really_ exist.
  342. assert self.parentPath.exists()
  343. yield self.parentPath
  344. else:
  345. smp = self.pathEntry.pythonPath._smartPath(fn)
  346. if smp.exists():
  347. yield smp
  348. else:
  349. yield self.parentPath
  350. class PathEntry(_ModuleIteratorHelper):
  351. """
  352. I am a proxy for a single entry on sys.path.
  353. @ivar filePath: a FilePath-like object pointing at the filesystem location
  354. or archive file where this path entry is stored.
  355. @ivar pythonPath: a PythonPath instance.
  356. """
  357. def __init__(self, filePath, pythonPath):
  358. """
  359. Create a PathEntry. This is a private constructor.
  360. """
  361. self.filePath = filePath
  362. self.pythonPath = pythonPath
  363. def _getEntry(self):
  364. return self
  365. def __repr__(self) -> str:
  366. return f"PathEntry<{self.filePath!r}>"
  367. def _packagePaths(self):
  368. yield self.filePath
  369. class IPathImportMapper(Interface):
  370. """
  371. This is an internal interface, used to map importers to factories for
  372. FilePath-like objects.
  373. """
  374. def mapPath(pathLikeString):
  375. """
  376. Return a FilePath-like object.
  377. @param pathLikeString: a path-like string, like one that might be
  378. passed to an import hook.
  379. @return: a L{FilePath}, or something like it (currently only a
  380. L{ZipPath}, but more might be added later).
  381. """
  382. @implementer(IPathImportMapper)
  383. class _DefaultMapImpl:
  384. """Wrapper for the default importer, i.e. None."""
  385. def mapPath(self, fsPathString):
  386. return FilePath(fsPathString)
  387. _theDefaultMapper = _DefaultMapImpl()
  388. @implementer(IPathImportMapper)
  389. class _ZipMapImpl:
  390. """IPathImportMapper implementation for zipimport.ZipImporter."""
  391. def __init__(self, importer):
  392. self.importer = importer
  393. def mapPath(self, fsPathString):
  394. """
  395. Map the given FS path to a ZipPath, by looking at the ZipImporter's
  396. "archive" attribute and using it as our ZipArchive root, then walking
  397. down into the archive from there.
  398. @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance.
  399. """
  400. za = ZipArchive(self.importer.archive)
  401. myPath = FilePath(self.importer.archive)
  402. itsPath = FilePath(fsPathString)
  403. if myPath == itsPath:
  404. return za
  405. # This is NOT a general-purpose rule for sys.path or __file__:
  406. # zipimport specifically uses regular OS path syntax in its
  407. # pathnames, even though zip files specify that slashes are always
  408. # the separator, regardless of platform.
  409. segs = itsPath.segmentsFrom(myPath)
  410. zp = za
  411. for seg in segs:
  412. zp = zp.child(seg)
  413. return zp
  414. registerAdapter(_ZipMapImpl, zipimport.zipimporter, IPathImportMapper)
  415. def _defaultSysPathFactory():
  416. """
  417. Provide the default behavior of PythonPath's sys.path factory, which is to
  418. return the current value of sys.path.
  419. @return: L{sys.path}
  420. """
  421. return sys.path
  422. class PythonPath:
  423. """
  424. I represent the very top of the Python object-space, the module list in
  425. C{sys.path} and the modules list in C{sys.modules}.
  426. @ivar _sysPath: A sequence of strings like C{sys.path}. This attribute is
  427. read-only.
  428. @ivar sysPath: The current value of the module search path list.
  429. @type sysPath: C{list}
  430. @ivar moduleDict: A dictionary mapping string module names to module
  431. objects, like C{sys.modules}.
  432. @ivar sysPathHooks: A list of PEP-302 path hooks, like C{sys.path_hooks}.
  433. @ivar moduleLoader: A function that takes a fully-qualified python name and
  434. returns a module, like L{twisted.python.reflect.namedAny}.
  435. """
  436. def __init__(
  437. self,
  438. sysPath=None,
  439. moduleDict=sys.modules,
  440. sysPathHooks=sys.path_hooks,
  441. importerCache=sys.path_importer_cache,
  442. moduleLoader=namedAny,
  443. sysPathFactory=None,
  444. ):
  445. """
  446. Create a PythonPath. You almost certainly want to use
  447. modules.theSystemPath, or its aliased methods, rather than creating a
  448. new instance yourself, though.
  449. All parameters are optional, and if unspecified, will use 'system'
  450. equivalents that makes this PythonPath like the global L{theSystemPath}
  451. instance.
  452. @param sysPath: a sys.path-like list to use for this PythonPath, to
  453. specify where to load modules from.
  454. @param moduleDict: a sys.modules-like dictionary to use for keeping
  455. track of what modules this PythonPath has loaded.
  456. @param sysPathHooks: sys.path_hooks-like list of PEP-302 path hooks to
  457. be used for this PythonPath, to determie which importers should be
  458. used.
  459. @param importerCache: a sys.path_importer_cache-like list of PEP-302
  460. importers. This will be used in conjunction with the given
  461. sysPathHooks.
  462. @param moduleLoader: a module loader function which takes a string and
  463. returns a module. That is to say, it is like L{namedAny} - *not* like
  464. L{__import__}.
  465. @param sysPathFactory: a 0-argument callable which returns the current
  466. value of a sys.path-like list of strings. Specify either this, or
  467. sysPath, not both. This alternative interface is provided because the
  468. way the Python import mechanism works, you can re-bind the 'sys.path'
  469. name and that is what is used for current imports, so it must be a
  470. factory rather than a value to deal with modification by rebinding
  471. rather than modification by mutation. Note: it is not recommended to
  472. rebind sys.path. Although this mechanism can deal with that, it is a
  473. subtle point which some tools that it is easy for tools which interact
  474. with sys.path to miss.
  475. """
  476. if sysPath is not None:
  477. sysPathFactory = lambda: sysPath
  478. elif sysPathFactory is None:
  479. sysPathFactory = _defaultSysPathFactory
  480. self._sysPathFactory = sysPathFactory
  481. self._sysPath = sysPath
  482. self.moduleDict = moduleDict
  483. self.sysPathHooks = sysPathHooks
  484. self.importerCache = importerCache
  485. self.moduleLoader = moduleLoader
  486. @property
  487. def sysPath(self):
  488. """
  489. Retrieve the current value of the module search path list.
  490. """
  491. return self._sysPathFactory()
  492. def _findEntryPathString(self, modobj):
  493. """
  494. Determine where a given Python module object came from by looking at path
  495. entries.
  496. """
  497. topPackageObj = modobj
  498. while "." in topPackageObj.__name__:
  499. topPackageObj = self.moduleDict[
  500. ".".join(topPackageObj.__name__.split(".")[:-1])
  501. ]
  502. if _isPackagePath(FilePath(topPackageObj.__file__)):
  503. # if package 'foo' is on sys.path at /a/b/foo, package 'foo's
  504. # __file__ will be /a/b/foo/__init__.py, and we are looking for
  505. # /a/b here, the path-entry; so go up two steps.
  506. rval = dirname(dirname(topPackageObj.__file__))
  507. else:
  508. # the module is completely top-level, not within any packages. The
  509. # path entry it's on is just its dirname.
  510. rval = dirname(topPackageObj.__file__)
  511. # There are probably some awful tricks that an importer could pull
  512. # which would break this, so let's just make sure... it's a loaded
  513. # module after all, which means that its path MUST be in
  514. # path_importer_cache according to PEP 302 -glyph
  515. if rval not in self.importerCache:
  516. warnings.warn(
  517. "%s (for module %s) not in path importer cache "
  518. "(PEP 302 violation - check your local configuration)."
  519. % (rval, modobj.__name__),
  520. stacklevel=3,
  521. )
  522. return rval
  523. def _smartPath(self, pathName):
  524. """
  525. Given a path entry from sys.path which may refer to an importer,
  526. return the appropriate FilePath-like instance.
  527. @param pathName: a str describing the path.
  528. @return: a FilePath-like object.
  529. """
  530. importr = self.importerCache.get(pathName, _nothing)
  531. if importr is _nothing:
  532. for hook in self.sysPathHooks:
  533. try:
  534. importr = hook(pathName)
  535. except ImportError:
  536. pass
  537. if importr is _nothing: # still
  538. importr = None
  539. return IPathImportMapper(importr, _theDefaultMapper).mapPath(pathName)
  540. def iterEntries(self):
  541. """
  542. Iterate the entries on my sysPath.
  543. @return: a generator yielding PathEntry objects
  544. """
  545. for pathName in self.sysPath:
  546. fp = self._smartPath(pathName)
  547. yield PathEntry(fp, self)
  548. def __getitem__(self, modname):
  549. """
  550. Get a python module by its given fully-qualified name.
  551. @param modname: The fully-qualified Python module name to load.
  552. @type modname: C{str}
  553. @return: an object representing the module identified by C{modname}
  554. @rtype: L{PythonModule}
  555. @raise KeyError: if the module name is not a valid module name, or no
  556. such module can be identified as loadable.
  557. """
  558. # See if the module is already somewhere in Python-land.
  559. moduleObject = self.moduleDict.get(modname)
  560. if moduleObject is not None:
  561. # we need 2 paths; one of the path entry and one for the module.
  562. pe = PathEntry(
  563. self._smartPath(self._findEntryPathString(moduleObject)), self
  564. )
  565. mp = self._smartPath(moduleObject.__file__)
  566. return PythonModule(modname, mp, pe)
  567. # Recurse if we're trying to get a submodule.
  568. if "." in modname:
  569. pkg = self
  570. for name in modname.split("."):
  571. pkg = pkg[name]
  572. return pkg
  573. # Finally do the slowest possible thing and iterate
  574. for module in self.iterModules():
  575. if module.name == modname:
  576. return module
  577. raise KeyError(modname)
  578. def __contains__(self, module):
  579. """
  580. Check to see whether or not a module exists on my import path.
  581. @param module: The name of the module to look for on my import path.
  582. @type module: C{str}
  583. """
  584. try:
  585. self.__getitem__(module)
  586. return True
  587. except KeyError:
  588. return False
  589. def __repr__(self) -> str:
  590. """
  591. Display my sysPath and moduleDict in a string representation.
  592. """
  593. return f"PythonPath({self.sysPath!r},{self.moduleDict!r})"
  594. def iterModules(self):
  595. """
  596. Yield all top-level modules on my sysPath.
  597. """
  598. for entry in self.iterEntries():
  599. yield from entry.iterModules()
  600. def walkModules(self, importPackages=False):
  601. """
  602. Similar to L{iterModules}, this yields every module on the path, then every
  603. submodule in each package or entry.
  604. """
  605. for package in self.iterModules():
  606. yield from package.walkModules(importPackages=False)
  607. theSystemPath = PythonPath()
  608. def walkModules(importPackages=False):
  609. """
  610. Deeply iterate all modules on the global python path.
  611. @param importPackages: Import packages as they are seen.
  612. """
  613. return theSystemPath.walkModules(importPackages=importPackages)
  614. def iterModules():
  615. """
  616. Iterate all modules and top-level packages on the global Python path, but
  617. do not descend into packages.
  618. """
  619. return theSystemPath.iterModules()
  620. def getModule(moduleName):
  621. """
  622. Retrieve a module from the system path.
  623. """
  624. return theSystemPath[moduleName]