oxython 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. Cython/Build/BuildExecutable.py +156 -0
  2. Cython/Build/Cache.py +198 -0
  3. Cython/Build/Cythonize.py +349 -0
  4. Cython/Build/Dependencies.py +1320 -0
  5. Cython/Build/Distutils.py +1 -0
  6. Cython/Build/Inline.py +467 -0
  7. Cython/Build/IpythonMagic.py +559 -0
  8. Cython/Build/SharedModule.py +165 -0
  9. Cython/Build/Tests/TestCyCache.py +222 -0
  10. Cython/Build/Tests/TestCythonizeArgsParser.py +480 -0
  11. Cython/Build/Tests/TestDependencies.py +133 -0
  12. Cython/Build/Tests/TestInline.py +177 -0
  13. Cython/Build/Tests/TestIpythonMagic.py +303 -0
  14. Cython/Build/Tests/TestRecythonize.py +212 -0
  15. Cython/Build/Tests/TestStripLiterals.py +155 -0
  16. Cython/Build/Tests/__init__.py +1 -0
  17. Cython/Build/__init__.py +11 -0
  18. Cython/CodeWriter.py +825 -0
  19. Cython/Compiler/AnalysedTreeTransforms.py +97 -0
  20. Cython/Compiler/Annotate.py +328 -0
  21. Cython/Compiler/AutoDocTransforms.py +320 -0
  22. Cython/Compiler/Buffer.py +679 -0
  23. Cython/Compiler/Builtin.py +1102 -0
  24. Cython/Compiler/CmdLine.py +373 -0
  25. Cython/Compiler/Code.pxd +154 -0
  26. Cython/Compiler/Code.py +3760 -0
  27. Cython/Compiler/CodeGeneration.py +33 -0
  28. Cython/Compiler/CythonScope.py +208 -0
  29. Cython/Compiler/Dataclass.py +890 -0
  30. Cython/Compiler/DebugFlags.py +24 -0
  31. Cython/Compiler/Errors.py +310 -0
  32. Cython/Compiler/ExprNodes.py +16319 -0
  33. Cython/Compiler/FlowControl.pxd +112 -0
  34. Cython/Compiler/FlowControl.py +1575 -0
  35. Cython/Compiler/FusedNode.py +978 -0
  36. Cython/Compiler/Future.py +16 -0
  37. Cython/Compiler/Interpreter.py +57 -0
  38. Cython/Compiler/Lexicon.py +442 -0
  39. Cython/Compiler/LineTable.py +114 -0
  40. Cython/Compiler/Main.py +879 -0
  41. Cython/Compiler/MatchCaseNodes.py +2200 -0
  42. Cython/Compiler/MemoryView.py +930 -0
  43. Cython/Compiler/ModuleNode.py +4558 -0
  44. Cython/Compiler/Naming.py +370 -0
  45. Cython/Compiler/Nodes.py +11334 -0
  46. Cython/Compiler/Optimize.py +5563 -0
  47. Cython/Compiler/Options.py +841 -0
  48. Cython/Compiler/ParseTreeTransforms.pxd +80 -0
  49. Cython/Compiler/ParseTreeTransforms.py +4808 -0
  50. Cython/Compiler/Parsing.pxd +9 -0
  51. Cython/Compiler/Parsing.py +5442 -0
  52. Cython/Compiler/Pipeline.py +439 -0
  53. Cython/Compiler/PyrexTypes.py +6588 -0
  54. Cython/Compiler/Pythran.py +232 -0
  55. Cython/Compiler/Scanning.pxd +74 -0
  56. Cython/Compiler/Scanning.py +771 -0
  57. Cython/Compiler/StringEncoding.py +354 -0
  58. Cython/Compiler/Symtab.py +3122 -0
  59. Cython/Compiler/Tests/TestBuffer.py +105 -0
  60. Cython/Compiler/Tests/TestBuiltin.py +196 -0
  61. Cython/Compiler/Tests/TestCmdLine.py +652 -0
  62. Cython/Compiler/Tests/TestCode.py +145 -0
  63. Cython/Compiler/Tests/TestFlowControl.py +65 -0
  64. Cython/Compiler/Tests/TestGrammar.py +202 -0
  65. Cython/Compiler/Tests/TestMemView.py +71 -0
  66. Cython/Compiler/Tests/TestParseTreeTransforms.py +285 -0
  67. Cython/Compiler/Tests/TestScanning.py +132 -0
  68. Cython/Compiler/Tests/TestSignatureMatching.py +73 -0
  69. Cython/Compiler/Tests/TestStringEncoding.py +20 -0
  70. Cython/Compiler/Tests/TestTreeFragment.py +63 -0
  71. Cython/Compiler/Tests/TestTreePath.py +103 -0
  72. Cython/Compiler/Tests/TestTypes.py +119 -0
  73. Cython/Compiler/Tests/TestUtilityLoad.py +112 -0
  74. Cython/Compiler/Tests/TestVisitor.py +119 -0
  75. Cython/Compiler/Tests/Utils.py +36 -0
  76. Cython/Compiler/Tests/__init__.py +1 -0
  77. Cython/Compiler/TreeFragment.py +279 -0
  78. Cython/Compiler/TreePath.py +303 -0
  79. Cython/Compiler/TypeInference.py +626 -0
  80. Cython/Compiler/TypeSlots.py +1330 -0
  81. Cython/Compiler/UFuncs.py +317 -0
  82. Cython/Compiler/UtilNodes.py +389 -0
  83. Cython/Compiler/UtilityCode.py +354 -0
  84. Cython/Compiler/Version.py +8 -0
  85. Cython/Compiler/Visitor.pxd +52 -0
  86. Cython/Compiler/Visitor.py +914 -0
  87. Cython/Compiler/__init__.py +1 -0
  88. Cython/Coverage.py +448 -0
  89. Cython/Debugger/Cygdb.py +214 -0
  90. Cython/Debugger/DebugWriter.py +82 -0
  91. Cython/Debugger/Tests/TestLibCython.py +280 -0
  92. Cython/Debugger/Tests/__init__.py +1 -0
  93. Cython/Debugger/Tests/cfuncs.c +8 -0
  94. Cython/Debugger/Tests/codefile +49 -0
  95. Cython/Debugger/Tests/test_libcython_in_gdb.py +580 -0
  96. Cython/Debugger/Tests/test_libpython_in_gdb.py +90 -0
  97. Cython/Debugger/__init__.py +1 -0
  98. Cython/Debugger/libcython.py +1548 -0
  99. Cython/Debugger/libpython.py +2821 -0
  100. Cython/Debugging.py +20 -0
  101. Cython/Distutils/__init__.py +2 -0
  102. Cython/Distutils/build_ext.py +143 -0
  103. Cython/Distutils/extension.py +96 -0
  104. Cython/Distutils/old_build_ext.py +351 -0
  105. Cython/Includes/cpython/__init__.pxd +173 -0
  106. Cython/Includes/cpython/array.pxd +159 -0
  107. Cython/Includes/cpython/bool.pxd +37 -0
  108. Cython/Includes/cpython/buffer.pxd +112 -0
  109. Cython/Includes/cpython/bytearray.pxd +33 -0
  110. Cython/Includes/cpython/bytes.pxd +200 -0
  111. Cython/Includes/cpython/cellobject.pxd +35 -0
  112. Cython/Includes/cpython/ceval.pxd +8 -0
  113. Cython/Includes/cpython/codecs.pxd +121 -0
  114. Cython/Includes/cpython/complex.pxd +60 -0
  115. Cython/Includes/cpython/contextvars.pxd +145 -0
  116. Cython/Includes/cpython/conversion.pxd +36 -0
  117. Cython/Includes/cpython/datetime.pxd +395 -0
  118. Cython/Includes/cpython/descr.pxd +26 -0
  119. Cython/Includes/cpython/dict.pxd +268 -0
  120. Cython/Includes/cpython/exc.pxd +263 -0
  121. Cython/Includes/cpython/fileobject.pxd +57 -0
  122. Cython/Includes/cpython/float.pxd +56 -0
  123. Cython/Includes/cpython/frozendict.pxd +37 -0
  124. Cython/Includes/cpython/function.pxd +65 -0
  125. Cython/Includes/cpython/genobject.pxd +25 -0
  126. Cython/Includes/cpython/getargs.pxd +12 -0
  127. Cython/Includes/cpython/instance.pxd +25 -0
  128. Cython/Includes/cpython/iterator.pxd +36 -0
  129. Cython/Includes/cpython/iterobject.pxd +24 -0
  130. Cython/Includes/cpython/list.pxd +144 -0
  131. Cython/Includes/cpython/long.pxd +180 -0
  132. Cython/Includes/cpython/longintrepr.pxd +14 -0
  133. Cython/Includes/cpython/mapping.pxd +63 -0
  134. Cython/Includes/cpython/marshal.pxd +66 -0
  135. Cython/Includes/cpython/mem.pxd +120 -0
  136. Cython/Includes/cpython/memoryview.pxd +50 -0
  137. Cython/Includes/cpython/method.pxd +49 -0
  138. Cython/Includes/cpython/module.pxd +208 -0
  139. Cython/Includes/cpython/number.pxd +258 -0
  140. Cython/Includes/cpython/object.pxd +430 -0
  141. Cython/Includes/cpython/pycapsule.pxd +143 -0
  142. Cython/Includes/cpython/pylifecycle.pxd +68 -0
  143. Cython/Includes/cpython/pyport.pxd +8 -0
  144. Cython/Includes/cpython/pystate.pxd +95 -0
  145. Cython/Includes/cpython/pythread.pxd +53 -0
  146. Cython/Includes/cpython/ref.pxd +141 -0
  147. Cython/Includes/cpython/sentinel.pxd +17 -0
  148. Cython/Includes/cpython/sequence.pxd +134 -0
  149. Cython/Includes/cpython/set.pxd +119 -0
  150. Cython/Includes/cpython/slice.pxd +70 -0
  151. Cython/Includes/cpython/time.pxd +129 -0
  152. Cython/Includes/cpython/tuple.pxd +72 -0
  153. Cython/Includes/cpython/type.pxd +146 -0
  154. Cython/Includes/cpython/unicode.pxd +639 -0
  155. Cython/Includes/cpython/version.pxd +32 -0
  156. Cython/Includes/cpython/weakref.pxd +78 -0
  157. Cython/Includes/libc/__init__.pxd +1 -0
  158. Cython/Includes/libc/complex.pxd +35 -0
  159. Cython/Includes/libc/errno.pxd +127 -0
  160. Cython/Includes/libc/float.pxd +43 -0
  161. Cython/Includes/libc/limits.pxd +28 -0
  162. Cython/Includes/libc/locale.pxd +46 -0
  163. Cython/Includes/libc/math.pxd +209 -0
  164. Cython/Includes/libc/setjmp.pxd +10 -0
  165. Cython/Includes/libc/signal.pxd +64 -0
  166. Cython/Includes/libc/stdbool.pxd +5 -0
  167. Cython/Includes/libc/stddef.pxd +9 -0
  168. Cython/Includes/libc/stdint.pxd +105 -0
  169. Cython/Includes/libc/stdio.pxd +80 -0
  170. Cython/Includes/libc/stdlib.pxd +72 -0
  171. Cython/Includes/libc/string.pxd +50 -0
  172. Cython/Includes/libc/threads.pxd +234 -0
  173. Cython/Includes/libc/time.pxd +52 -0
  174. Cython/Includes/libcpp/__init__.pxd +4 -0
  175. Cython/Includes/libcpp/algorithm.pxd +320 -0
  176. Cython/Includes/libcpp/any.pxd +16 -0
  177. Cython/Includes/libcpp/atomic.pxd +59 -0
  178. Cython/Includes/libcpp/barrier.pxd +22 -0
  179. Cython/Includes/libcpp/bit.pxd +29 -0
  180. Cython/Includes/libcpp/cast.pxd +12 -0
  181. Cython/Includes/libcpp/cmath.pxd +518 -0
  182. Cython/Includes/libcpp/complex.pxd +106 -0
  183. Cython/Includes/libcpp/condition_variable.pxd +322 -0
  184. Cython/Includes/libcpp/deque.pxd +165 -0
  185. Cython/Includes/libcpp/exception.pxd +216 -0
  186. Cython/Includes/libcpp/execution.pxd +15 -0
  187. Cython/Includes/libcpp/forward_list.pxd +63 -0
  188. Cython/Includes/libcpp/functional.pxd +26 -0
  189. Cython/Includes/libcpp/future.pxd +103 -0
  190. Cython/Includes/libcpp/iterator.pxd +34 -0
  191. Cython/Includes/libcpp/latch.pxd +17 -0
  192. Cython/Includes/libcpp/limits.pxd +61 -0
  193. Cython/Includes/libcpp/list.pxd +117 -0
  194. Cython/Includes/libcpp/map.pxd +252 -0
  195. Cython/Includes/libcpp/memory.pxd +115 -0
  196. Cython/Includes/libcpp/mutex.pxd +387 -0
  197. Cython/Includes/libcpp/numbers.pxd +15 -0
  198. Cython/Includes/libcpp/numeric.pxd +131 -0
  199. Cython/Includes/libcpp/optional.pxd +34 -0
  200. Cython/Includes/libcpp/pair.pxd +1 -0
  201. Cython/Includes/libcpp/queue.pxd +25 -0
  202. Cython/Includes/libcpp/random.pxd +166 -0
  203. Cython/Includes/libcpp/semaphore.pxd +43 -0
  204. Cython/Includes/libcpp/set.pxd +228 -0
  205. Cython/Includes/libcpp/shared_mutex.pxd +96 -0
  206. Cython/Includes/libcpp/span.pxd +87 -0
  207. Cython/Includes/libcpp/stack.pxd +11 -0
  208. Cython/Includes/libcpp/stop_token.pxd +117 -0
  209. Cython/Includes/libcpp/string.pxd +355 -0
  210. Cython/Includes/libcpp/string_view.pxd +183 -0
  211. Cython/Includes/libcpp/typeindex.pxd +15 -0
  212. Cython/Includes/libcpp/typeinfo.pxd +10 -0
  213. Cython/Includes/libcpp/unordered_map.pxd +193 -0
  214. Cython/Includes/libcpp/unordered_set.pxd +152 -0
  215. Cython/Includes/libcpp/utility.pxd +30 -0
  216. Cython/Includes/libcpp/vector.pxd +186 -0
  217. Cython/Includes/numpy/math.pxd +150 -0
  218. Cython/Includes/openmp.pxd +50 -0
  219. Cython/Includes/posix/__init__.pxd +1 -0
  220. Cython/Includes/posix/dlfcn.pxd +14 -0
  221. Cython/Includes/posix/fcntl.pxd +86 -0
  222. Cython/Includes/posix/ioctl.pxd +4 -0
  223. Cython/Includes/posix/mman.pxd +101 -0
  224. Cython/Includes/posix/resource.pxd +57 -0
  225. Cython/Includes/posix/select.pxd +21 -0
  226. Cython/Includes/posix/signal.pxd +73 -0
  227. Cython/Includes/posix/stat.pxd +98 -0
  228. Cython/Includes/posix/stdio.pxd +37 -0
  229. Cython/Includes/posix/stdlib.pxd +29 -0
  230. Cython/Includes/posix/strings.pxd +9 -0
  231. Cython/Includes/posix/time.pxd +71 -0
  232. Cython/Includes/posix/types.pxd +30 -0
  233. Cython/Includes/posix/uio.pxd +26 -0
  234. Cython/Includes/posix/unistd.pxd +271 -0
  235. Cython/Includes/posix/wait.pxd +38 -0
  236. Cython/LZSS.py +184 -0
  237. Cython/Plex/Actions.pxd +24 -0
  238. Cython/Plex/Actions.py +119 -0
  239. Cython/Plex/DFA.pxd +14 -0
  240. Cython/Plex/DFA.py +164 -0
  241. Cython/Plex/Errors.py +48 -0
  242. Cython/Plex/Lexicons.py +178 -0
  243. Cython/Plex/Machines.pxd +36 -0
  244. Cython/Plex/Machines.py +238 -0
  245. Cython/Plex/Regexps.py +535 -0
  246. Cython/Plex/Scanners.pxd +45 -0
  247. Cython/Plex/Scanners.py +328 -0
  248. Cython/Plex/Transitions.pxd +14 -0
  249. Cython/Plex/Transitions.py +239 -0
  250. Cython/Plex/__init__.py +34 -0
  251. Cython/Runtime/__init__.py +1 -0
  252. Cython/Runtime/refnanny.pyx +237 -0
  253. Cython/Shadow.py +1172 -0
  254. Cython/StringIOTree.py +169 -0
  255. Cython/Tempita/__init__.py +4 -0
  256. Cython/Tempita/_looper.py +154 -0
  257. Cython/Tempita/_tempita.py +1087 -0
  258. Cython/TestUtils.py +472 -0
  259. Cython/Tests/TestCodeWriter.py +128 -0
  260. Cython/Tests/TestCythonUtils.py +237 -0
  261. Cython/Tests/TestJediTyper.py +223 -0
  262. Cython/Tests/TestShadow.py +125 -0
  263. Cython/Tests/TestStringIOTree.py +68 -0
  264. Cython/Tests/TestTestUtils.py +89 -0
  265. Cython/Tests/__init__.py +1 -0
  266. Cython/Tests/xmlrunner.py +390 -0
  267. Cython/Utility/AsyncGen.c +1152 -0
  268. Cython/Utility/Buffer.c +866 -0
  269. Cython/Utility/BufferFormatFromTypeInfo.pxd +2 -0
  270. Cython/Utility/Builtins.c +1068 -0
  271. Cython/Utility/CConvert.pyx +153 -0
  272. Cython/Utility/CMath.c +104 -0
  273. Cython/Utility/CommonStructures.c +244 -0
  274. Cython/Utility/Complex.c +378 -0
  275. Cython/Utility/Coroutine.c +2344 -0
  276. Cython/Utility/CpdefEnums.pyx +119 -0
  277. Cython/Utility/CppConvert.pyx +284 -0
  278. Cython/Utility/CppSupport.cpp +151 -0
  279. Cython/Utility/CythonFunction.c +2143 -0
  280. Cython/Utility/Dataclasses.c +101 -0
  281. Cython/Utility/Embed.c +129 -0
  282. Cython/Utility/Exceptions.c +1331 -0
  283. Cython/Utility/Exceptions_Cy.pyx +109 -0
  284. Cython/Utility/ExtensionTypes.c +1199 -0
  285. Cython/Utility/FunctionArguments.c +1052 -0
  286. Cython/Utility/FusedFunction.pyx +44 -0
  287. Cython/Utility/ImportExport.c +972 -0
  288. Cython/Utility/MatchCase.c +985 -0
  289. Cython/Utility/MatchCase_Cy.pyx +12 -0
  290. Cython/Utility/MemoryView.pxd +108 -0
  291. Cython/Utility/MemoryView.pyx +1499 -0
  292. Cython/Utility/MemoryView_C.c +1056 -0
  293. Cython/Utility/ModuleSetupCode.c +3349 -0
  294. Cython/Utility/NumpyImportArray.c +46 -0
  295. Cython/Utility/ObjectHandling.c +3404 -0
  296. Cython/Utility/Optimize.c +2575 -0
  297. Cython/Utility/Overflow.c +378 -0
  298. Cython/Utility/Profile.c +736 -0
  299. Cython/Utility/StringTools.c +1534 -0
  300. Cython/Utility/Synchronization.c +438 -0
  301. Cython/Utility/TString.c +369 -0
  302. Cython/Utility/TestCyUtilityLoader.pyx +8 -0
  303. Cython/Utility/TestCythonScope.pyx +75 -0
  304. Cython/Utility/TestUtilityLoader.c +12 -0
  305. Cython/Utility/TypeConversion.c +1588 -0
  306. Cython/Utility/UFuncs.pyx +50 -0
  307. Cython/Utility/UFuncs_C.c +89 -0
  308. Cython/Utility/__init__.py +28 -0
  309. Cython/Utility/arrayarray.h +190 -0
  310. Cython/Utils.py +682 -0
  311. Cython/__init__.py +12 -0
  312. Cython/py.typed +0 -0
  313. cython.py +29 -0
  314. oxython-0.1.0.dist-info/METADATA +138 -0
  315. oxython-0.1.0.dist-info/RECORD +321 -0
  316. oxython-0.1.0.dist-info/WHEEL +5 -0
  317. oxython-0.1.0.dist-info/entry_points.txt +4 -0
  318. oxython-0.1.0.dist-info/top_level.txt +3 -0
  319. pyximport/__init__.py +4 -0
  320. pyximport/pyxbuild.py +160 -0
  321. pyximport/pyximport.py +482 -0
@@ -0,0 +1,1320 @@
1
+ import cython
2
+
3
+ import collections
4
+ import os
5
+ import re, sys, time
6
+ from glob import iglob
7
+ from io import StringIO
8
+ from os.path import relpath as _relpath
9
+ from .Cache import Cache, FingerprintFlags
10
+
11
+ from collections.abc import Iterable
12
+ from functools import partial
13
+
14
+ try:
15
+ import pythran
16
+ except Exception:
17
+ pythran = None
18
+
19
+ from .. import Utils
20
+ from ..Utils import (cached_function, cached_method, path_exists,
21
+ copy_file_to_dir_if_newer, is_package_dir, write_depfile)
22
+ from ..Compiler import Errors
23
+ from ..Compiler.Main import Context
24
+ from ..Compiler import Options
25
+ from ..Compiler.Options import (CompilationOptions, default_options,
26
+ get_directive_defaults)
27
+
28
+ join_path = cached_function(os.path.join)
29
+ copy_once_if_newer = cached_function(copy_file_to_dir_if_newer)
30
+ safe_makedirs_once = cached_function(partial(os.makedirs, exist_ok=True))
31
+
32
+
33
+ @cython.cfunc
34
+ def _make_relative(file_paths, base=None) -> list[str]:
35
+ if not base:
36
+ base = os.getcwd()
37
+ if base[-1] != os.path.sep:
38
+ base += os.path.sep
39
+ return [_relpath(path, base) if path.startswith(base) else path
40
+ for path in file_paths]
41
+
42
+
43
+ def extended_iglob(pattern):
44
+ if '{' in pattern:
45
+ m = re.match('(.*){([^}]+)}(.*)', pattern)
46
+ if m:
47
+ before, switch, after = m.groups()
48
+ for case in switch.split(','):
49
+ for path in extended_iglob(before + case + after):
50
+ yield path
51
+ return
52
+
53
+ # We always accept '/' and also '\' on Windows,
54
+ # because '/' is generally common for relative paths.
55
+ if '**/' in pattern or os.sep == '\\' and '**\\' in pattern:
56
+ seen = set()
57
+ first, rest = re.split(r'\*\*[%s]' % ('/\\\\' if os.sep == '\\' else '/'), pattern, maxsplit=1)
58
+ if first:
59
+ first = iglob(first + os.sep)
60
+ else:
61
+ first = ['']
62
+ for root in first:
63
+ for path in extended_iglob(join_path(root, rest)):
64
+ if path not in seen:
65
+ seen.add(path)
66
+ yield path
67
+ for path in extended_iglob(join_path(root, '*', '**', rest)):
68
+ if path not in seen:
69
+ seen.add(path)
70
+ yield path
71
+ else:
72
+ for path in iglob(pattern):
73
+ yield path
74
+
75
+
76
+ def nonempty(it, error_msg="expected non-empty iterator"):
77
+ empty = True
78
+ for value in it:
79
+ empty = False
80
+ yield value
81
+ if empty:
82
+ raise ValueError(error_msg)
83
+
84
+
85
+ def update_pythran_extension(ext):
86
+ if pythran is None:
87
+ raise RuntimeError("You first need to install Pythran to use the np_pythran directive.")
88
+ try:
89
+ pythran_ext = pythran.config.make_extension(python=True)
90
+ except TypeError: # older pythran version only
91
+ pythran_ext = pythran.config.make_extension()
92
+
93
+ ext.include_dirs.extend(pythran_ext['include_dirs'])
94
+ ext.extra_compile_args.extend(pythran_ext['extra_compile_args'])
95
+ ext.extra_link_args.extend(pythran_ext['extra_link_args'])
96
+ ext.define_macros.extend(pythran_ext['define_macros'])
97
+ ext.undef_macros.extend(pythran_ext['undef_macros'])
98
+ ext.library_dirs.extend(pythran_ext['library_dirs'])
99
+ ext.libraries.extend(pythran_ext['libraries'])
100
+ ext.language = 'c++'
101
+
102
+ # These options are not compatible with the way normal Cython extensions work
103
+ for bad_option in ["-fwhole-program", "-fvisibility=hidden"]:
104
+ try:
105
+ ext.extra_compile_args.remove(bad_option)
106
+ except ValueError:
107
+ pass
108
+
109
+
110
+ def parse_list(s):
111
+ """
112
+ >>> parse_list("")
113
+ []
114
+ >>> parse_list("a")
115
+ ['a']
116
+ >>> parse_list("a b c")
117
+ ['a', 'b', 'c']
118
+ >>> parse_list("[a, b, c]")
119
+ ['a', 'b', 'c']
120
+ >>> parse_list('a " " b')
121
+ ['a', ' ', 'b']
122
+ >>> parse_list('[a, ",a", "a,", ",", ]')
123
+ ['a', ',a', 'a,', ',']
124
+ """
125
+ if len(s) >= 2 and s[0] == '[' and s[-1] == ']':
126
+ s = s[1:-1]
127
+ delimiter = ','
128
+ else:
129
+ delimiter = ' '
130
+ s, literals = strip_string_literals(s)
131
+ def unquote(literal):
132
+ literal = literal.strip()
133
+ if literal[0] in "'\"":
134
+ return literals[literal[1:-1]]
135
+ else:
136
+ return literal
137
+ return [unquote(item) for item in s.split(delimiter) if item.strip()]
138
+
139
+
140
+ transitive_str = object()
141
+ transitive_list = object()
142
+ bool_or = object()
143
+
144
+ distutils_settings = {
145
+ 'name': str,
146
+ 'sources': list,
147
+ 'define_macros': list,
148
+ 'undef_macros': list,
149
+ 'libraries': transitive_list,
150
+ 'library_dirs': transitive_list,
151
+ 'runtime_library_dirs': transitive_list,
152
+ 'include_dirs': transitive_list,
153
+ 'extra_objects': list,
154
+ 'extra_compile_args': transitive_list,
155
+ 'extra_link_args': transitive_list,
156
+ 'export_symbols': list,
157
+ 'depends': transitive_list,
158
+ 'language': transitive_str,
159
+ 'np_pythran': bool_or
160
+ }
161
+
162
+
163
+ @cython.cfunc
164
+ def _legacy_strtobool(val):
165
+ # Used to be "distutils.util.strtobool", adapted for deprecation warnings.
166
+ if val == "True":
167
+ return True
168
+ elif val == "False":
169
+ return False
170
+
171
+ import warnings
172
+ warnings.warn("The 'np_python' option requires 'True' or 'False'", category=DeprecationWarning)
173
+ val = val.lower()
174
+ if val in ('y', 'yes', 't', 'true', 'on', '1'):
175
+ return True
176
+ elif val in ('n', 'no', 'f', 'false', 'off', '0'):
177
+ return False
178
+ else:
179
+ raise ValueError("invalid truth value %r" % (val,))
180
+
181
+
182
+ class DistutilsInfo:
183
+
184
+ def __init__(self, source=None, exn=None):
185
+ self.values = {}
186
+ if source is not None:
187
+ source_lines = StringIO(source) if isinstance(source, str) else source
188
+ for line in source_lines:
189
+ line = line.lstrip()
190
+ if not line:
191
+ continue
192
+ if line[0] != '#':
193
+ break
194
+ line = line[1:].lstrip()
195
+ kind = next((k for k in ("distutils:","cython:") if line.startswith(k)), None)
196
+ if kind is not None:
197
+ key, _, value = [s.strip() for s in line[len(kind):].partition('=')]
198
+ type = distutils_settings.get(key, None)
199
+ if line.startswith("cython:") and type is None: continue
200
+ if type in (list, transitive_list):
201
+ value = parse_list(value)
202
+ if key == 'define_macros':
203
+ value = [tuple(macro.split('=', 1))
204
+ if '=' in macro else (macro, None)
205
+ for macro in value]
206
+ if type is bool_or:
207
+ value = _legacy_strtobool(value)
208
+ self.values[key] = value
209
+ elif exn is not None:
210
+ for key in distutils_settings:
211
+ if key in ('name', 'sources','np_pythran'):
212
+ continue
213
+ value = getattr(exn, key, None)
214
+ if value:
215
+ self.values[key] = value
216
+
217
+ def merge(self, other):
218
+ if other is None:
219
+ return self
220
+ for key, value in other.values.items():
221
+ type = distutils_settings[key]
222
+ if type is transitive_str and key not in self.values:
223
+ self.values[key] = value
224
+ elif type is transitive_list:
225
+ if key in self.values:
226
+ # Change a *copy* of the list (Trac #845)
227
+ all = self.values[key][:]
228
+ for v in value:
229
+ if v not in all:
230
+ all.append(v)
231
+ value = all
232
+ self.values[key] = value
233
+ elif type is bool_or:
234
+ self.values[key] = self.values.get(key, False) | value
235
+ return self
236
+
237
+ def subs(self, aliases):
238
+ if aliases is None:
239
+ return self
240
+ resolved = DistutilsInfo()
241
+ for key, value in self.values.items():
242
+ type = distutils_settings[key]
243
+ if type in [list, transitive_list]:
244
+ new_value_list = []
245
+ for v in value:
246
+ if v in aliases:
247
+ v = aliases[v]
248
+ if isinstance(v, list):
249
+ new_value_list += v
250
+ else:
251
+ new_value_list.append(v)
252
+ value = new_value_list
253
+ else:
254
+ if value in aliases:
255
+ value = aliases[value]
256
+ resolved.values[key] = value
257
+ return resolved
258
+
259
+ def apply(self, extension):
260
+ for key, value in self.values.items():
261
+ type = distutils_settings[key]
262
+ if type in [list, transitive_list]:
263
+ value = getattr(extension, key) + list(value)
264
+ setattr(extension, key, value)
265
+
266
+
267
+ _FIND_TOKEN = cython.declare(object, re.compile(r"""
268
+ (?P<comment> [#] ) |
269
+ (?P<brace> [{}] ) |
270
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
271
+ """, re.VERBOSE).search)
272
+
273
+ _FIND_STRING_TOKEN = cython.declare(object, re.compile(r"""
274
+ (?P<escape> [\\]+ ) (?P<escaped_quote> ['"] ) |
275
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
276
+ """, re.VERBOSE).search)
277
+
278
+ _FIND_FSTRING_TOKEN = cython.declare(object, re.compile(r"""
279
+ (?P<braces> [{]+ | [}]+ ) |
280
+ (?P<escape> [\\]+ ) (?P<escaped_quote> ['"] ) |
281
+ (?P<fstring> f )? (?P<quote> '+ | "+ )
282
+ """, re.VERBOSE).search)
283
+
284
+
285
+ def strip_string_literals(code: str, prefix: str = '__Pyx_L'):
286
+ """
287
+ Normalizes every string literal to be of the form '__Pyx_Lxxx',
288
+ returning the normalized code and a mapping of labels to
289
+ string literals.
290
+ """
291
+ new_code: list = []
292
+ literals: dict = {}
293
+ counter: cython.Py_ssize_t = 0
294
+ find_token = _FIND_TOKEN
295
+
296
+ def append_new_label(literal):
297
+ nonlocal counter
298
+ counter += 1
299
+ label = f"{prefix}{counter}_"
300
+ literals[label] = literal
301
+ new_code.append(label)
302
+
303
+ def parse_string(quote_type: str, start: cython.Py_ssize_t, is_fstring: cython.bint) -> cython.Py_ssize_t:
304
+ charpos: cython.Py_ssize_t = start
305
+
306
+ find_token = _FIND_FSTRING_TOKEN if is_fstring else _FIND_STRING_TOKEN
307
+
308
+ while charpos != -1:
309
+ token = find_token(code, charpos)
310
+ if token is None:
311
+ # This probably indicates an unclosed string literal, i.e. a broken file.
312
+ append_new_label(code[start:])
313
+ charpos = -1
314
+ break
315
+ charpos = token.end()
316
+
317
+ if token['escape']:
318
+ if len(token['escape']) % 2 == 0 and token['escaped_quote'] == quote_type[0]:
319
+ # Quote is not actually escaped and might be part of a terminator, look at it next.
320
+ charpos -= 1
321
+
322
+ elif is_fstring and token['braces']:
323
+ # Formats or brace(s) in fstring.
324
+ if len(token['braces']) % 2 == 0:
325
+ # Normal brace characters in string.
326
+ continue
327
+ if token['braces'][-1] == '{':
328
+ if start < charpos-1:
329
+ append_new_label(code[start : charpos-1])
330
+ new_code.append('{')
331
+ start = charpos = parse_code(charpos, in_fstring=True)
332
+
333
+ elif token['quote'].startswith(quote_type):
334
+ # Closing quote found (potentially together with further, unrelated quotes).
335
+ charpos = token.start('quote')
336
+ if charpos > start:
337
+ append_new_label(code[start : charpos])
338
+ new_code.append(quote_type)
339
+ charpos += len(quote_type)
340
+ break
341
+
342
+ return charpos
343
+
344
+ def parse_code(start: cython.Py_ssize_t, in_fstring: cython.bint = False) -> cython.Py_ssize_t:
345
+ charpos: cython.Py_ssize_t = start
346
+ end: cython.Py_ssize_t
347
+ quote: str
348
+
349
+ while charpos != -1:
350
+ token = find_token(code, charpos)
351
+ if token is None:
352
+ new_code.append(code[start:])
353
+ charpos = -1
354
+ break
355
+ charpos = end = token.end()
356
+
357
+ if token['quote']:
358
+ quote = token['quote']
359
+ if len(quote) >= 6:
360
+ # Ignore empty tripple-quoted strings: '''''' or """"""
361
+ quote = quote[:len(quote) % 6]
362
+ if quote and len(quote) != 2:
363
+ if len(quote) > 3:
364
+ end -= len(quote) - 3
365
+ quote = quote[:3]
366
+ new_code.append(code[start:end])
367
+ start = charpos = parse_string(quote, end, is_fstring=token['fstring'])
368
+
369
+ elif token['comment']:
370
+ new_code.append(code[start:end])
371
+ charpos = code.find('\n', end)
372
+ append_new_label(code[end : charpos if charpos != -1 else None])
373
+ if charpos == -1:
374
+ break # EOF
375
+ start = charpos
376
+
377
+ elif in_fstring and token['brace']:
378
+ if token['brace'] == '}':
379
+ # Closing '}' of f-string.
380
+ charpos = end = token.start() + 1
381
+ new_code.append(code[start:end]) # with '}'
382
+ break
383
+ else:
384
+ # Starting a calculated format modifier inside of an f-string format.
385
+ end = token.start() + 1
386
+ new_code.append(code[start:end]) # with '{'
387
+ start = charpos = parse_code(end, in_fstring=True)
388
+
389
+ return charpos
390
+
391
+ parse_code(0)
392
+ return "".join(new_code), literals
393
+
394
+
395
+ # We need to allow spaces to allow for conditional compilation like
396
+ # IF ...:
397
+ # cimport ...
398
+ dependency_regex = re.compile(
399
+ r"(?:^ [ \t\f]* from [ \t\f]+ cython\.cimports\.([\w.]+) [ \t\f]+ c?import ) |"
400
+ r"(?:^ [ \t\f]* from [ \t\f]+ ([\w.]+) [ \t\f]+ cimport ) |"
401
+ r"(?:^ [ \t\f]* c?import [ \t\f]+ cython\.cimports\.([\w.]+) ) |"
402
+ r"(?:^ [ \t\f]* cimport [ \t\f]+ ([\w.]+ (?:[ \t\f]* , [ \t\f]* [\w.]+)*) ) |"
403
+ r"(?:^ [ \t\f]* cdef [ \t\f]+ extern [ \t\f]+ from [ \t\f]+ ['\"] ([^'\"]+) ['\"] ) |"
404
+ r"(?:^ [ \t\f]* include [ \t\f]+ ['\"] ([^'\"]+) ['\"] )",
405
+ re.MULTILINE | re.VERBOSE)
406
+ oxython_use_regex = re.compile(r"^[ \t\f]*use[ \t\f]+([^\n#]+)", re.MULTILINE)
407
+
408
+
409
+ def oxython_use_dependencies(source):
410
+ # 'use a::b::(c, d)' in oxython files: report modules like 'from a.b cimport c, d' does
411
+ modules = []
412
+ for m in oxython_use_regex.finditer(source):
413
+ for path in re.split(r",(?![^({]*[)}])", m.group(1)):
414
+ path = path.strip()
415
+ path = re.sub(r"[ \t]+as[ \t]+\w+$", "", path)
416
+ group = re.search(r"::[ \t]*[({]([^)}]*)[)}]$", path)
417
+ if group:
418
+ path = path[:group.start()]
419
+ names = [re.sub(r"[ \t]+as[ \t]+\w+$", "", n.strip()) for n in group.group(1).split(',') if n.strip()]
420
+ else:
421
+ names = []
422
+ parts = [p.strip() for p in path.split('::')]
423
+ level = 0
424
+ while parts and parts[0] == 'super':
425
+ parts.pop(0)
426
+ level += 1
427
+ if not parts or not all(re.match(r"^\w+$|^\*$", p) for p in parts):
428
+ continue
429
+ if parts[-1] == '*':
430
+ parts.pop()
431
+ module = '.' * level + '.'.join(parts)
432
+ if module:
433
+ modules.append(module)
434
+ modules.extend(module + '.' + n for n in names if re.match(r"^\w+$", n))
435
+ if not names and len(parts) > 1:
436
+ modules.append('.' * level + '.'.join(parts[:-1]))
437
+ return modules
438
+
439
+
440
+ dependency_after_from_regex = re.compile(
441
+ r"(?:^ [ \t\f]+ \( ([\w., \t\f]*) \) [ \t\f]* [#\n]) |"
442
+ r"(?:^ [ \t\f]+ ([\w., \t\f]*) [ \t\f]* [#\n])",
443
+ re.MULTILINE | re.VERBOSE)
444
+
445
+
446
+ def normalize_existing(base_path, rel_paths):
447
+ return normalize_existing0(os.path.dirname(base_path), tuple(set(rel_paths)))
448
+
449
+
450
+ @cached_function
451
+ def normalize_existing0(base_dir, rel_paths):
452
+ """
453
+ Given some base directory ``base_dir`` and a list of path names
454
+ ``rel_paths``, normalize each relative path name ``rel`` by
455
+ replacing it by ``os.path.join(base, rel)`` if that file exists.
456
+
457
+ Return a couple ``(normalized, needed_base)`` where ``normalized``
458
+ if the list of normalized file names and ``needed_base`` is
459
+ ``base_dir`` if we actually needed ``base_dir``. If no paths were
460
+ changed (for example, if all paths were already absolute), then
461
+ ``needed_base`` is ``None``.
462
+ """
463
+ normalized = []
464
+ needed_base = None
465
+ for rel in rel_paths:
466
+ if os.path.isabs(rel):
467
+ normalized.append(rel)
468
+ continue
469
+ path = join_path(base_dir, rel)
470
+ if path_exists(path):
471
+ normalized.append(os.path.normpath(path))
472
+ needed_base = base_dir
473
+ else:
474
+ normalized.append(rel)
475
+ return (normalized, needed_base)
476
+
477
+
478
+ def resolve_depends(depends, include_dirs):
479
+ include_dirs = tuple(include_dirs)
480
+ resolved = []
481
+ for depend in depends:
482
+ path = resolve_depend(depend, include_dirs)
483
+ if path is not None:
484
+ resolved.append(path)
485
+ return resolved
486
+
487
+
488
+ @cached_function
489
+ def resolve_depend(depend, include_dirs):
490
+ if depend[0] == '<' and depend[-1] == '>':
491
+ return None
492
+ for dir in include_dirs:
493
+ path = join_path(dir, depend)
494
+ if path_exists(path):
495
+ return os.path.normpath(path)
496
+ return None
497
+
498
+
499
+ @cached_function
500
+ def package(filename):
501
+ dir = os.path.dirname(os.path.abspath(str(filename)))
502
+ if dir != filename and is_package_dir(dir):
503
+ return package(dir) + (os.path.basename(dir),)
504
+ else:
505
+ return ()
506
+
507
+
508
+ @cached_function
509
+ def fully_qualified_name(filename):
510
+ module = os.path.splitext(os.path.basename(filename))[0]
511
+ return '.'.join(package(filename) + (module,))
512
+
513
+
514
+ @cached_function
515
+ def parse_dependencies(source_filename):
516
+ # Actual parsing is way too slow, so we use regular expressions.
517
+ # The only catch is that we must strip comments and string
518
+ # literals ahead of time.
519
+ with Utils.open_source_file(source_filename, error_handling='ignore') as fh:
520
+ source = fh.read()
521
+ distutils_info = DistutilsInfo(source)
522
+ source, literals = strip_string_literals(source)
523
+ source = source.replace('\\\n', ' ').replace('\t', ' ')
524
+
525
+ # TODO: pure mode
526
+ cimports = []
527
+ includes = []
528
+ externs = []
529
+ if source_filename.endswith(('.oxy', '.oxd', '.oxi')):
530
+ cimports.extend(oxython_use_dependencies(source))
531
+ for m in dependency_regex.finditer(source):
532
+ pycimports_from, cimport_from, pycimports_list, cimport_list, extern, include = m.groups()
533
+ if pycimports_from:
534
+ cimport_from = pycimports_from
535
+ if pycimports_list:
536
+ cimport_list = pycimports_list
537
+
538
+ if cimport_from:
539
+ cimports.append(cimport_from)
540
+ m_after_from = dependency_after_from_regex.search(source, pos=m.end())
541
+ if m_after_from:
542
+ multiline, one_line = m_after_from.groups()
543
+ subimports = multiline or one_line
544
+ cimports.extend("{}.{}".format(cimport_from, s.strip())
545
+ for s in subimports.split(','))
546
+
547
+ elif cimport_list:
548
+ cimports.extend(x.strip() for x in cimport_list.split(","))
549
+ elif extern:
550
+ externs.append(literals[extern])
551
+ else:
552
+ includes.append(literals[include])
553
+ return cimports, includes, externs, distutils_info
554
+
555
+
556
+ class DependencyTree:
557
+
558
+ def __init__(self, context, quiet=False):
559
+ self.context = context
560
+ self.quiet = quiet
561
+ self._transitive_cache = {}
562
+
563
+ def parse_dependencies(self, source_filename):
564
+ if path_exists(source_filename):
565
+ source_filename = os.path.normpath(source_filename)
566
+ return parse_dependencies(source_filename)
567
+
568
+ @cached_method
569
+ def included_files(self, filename):
570
+ # This is messy because included files are textually included, resolving
571
+ # cimports (but not includes) relative to the including file.
572
+ all = set()
573
+ for include in self.parse_dependencies(filename)[1]:
574
+ include_path = join_path(os.path.dirname(filename), include)
575
+ if not path_exists(include_path):
576
+ include_path = self.context.find_include_file(include, source_file_path=filename)
577
+ if include_path:
578
+ if '.' + os.path.sep in include_path:
579
+ include_path = os.path.normpath(include_path)
580
+ all.add(include_path)
581
+ all.update(self.included_files(include_path))
582
+ elif not self.quiet:
583
+ print("Unable to locate '%s' referenced from '%s'" % (filename, include))
584
+ return all
585
+
586
+ @cached_method
587
+ def cimports_externs_incdirs(self, filename):
588
+ # This is really ugly. Nested cimports are resolved with respect to the
589
+ # includer, but includes are resolved with respect to the includee.
590
+ cimports, includes, externs = self.parse_dependencies(filename)[:3]
591
+ cimports = set(cimports)
592
+ externs = set(externs)
593
+ incdirs = set()
594
+ for include in self.included_files(filename):
595
+ included_cimports, included_externs, included_incdirs = self.cimports_externs_incdirs(include)
596
+ cimports.update(included_cimports)
597
+ externs.update(included_externs)
598
+ incdirs.update(included_incdirs)
599
+ externs, incdir = normalize_existing(filename, externs)
600
+ if incdir:
601
+ incdirs.add(incdir)
602
+ return tuple(cimports), externs, incdirs
603
+
604
+ def cimports(self, filename):
605
+ return self.cimports_externs_incdirs(filename)[0]
606
+
607
+ def package(self, filename):
608
+ return package(filename)
609
+
610
+ def fully_qualified_name(self, filename):
611
+ return fully_qualified_name(filename)
612
+
613
+ @cached_method
614
+ def find_pxd(self, module, filename=None):
615
+ is_relative = module[0] == '.'
616
+ if is_relative and not filename:
617
+ raise NotImplementedError("New relative imports.")
618
+ if filename is not None:
619
+ module_path = module.split('.')
620
+ if is_relative:
621
+ module_path.pop(0) # just explicitly relative
622
+ package_path = list(self.package(filename))
623
+ while module_path and not module_path[0]:
624
+ try:
625
+ package_path.pop()
626
+ except IndexError:
627
+ return None # FIXME: error?
628
+ module_path.pop(0)
629
+ relative = '.'.join(package_path + module_path)
630
+ pxd = self.context.find_pxd_file(relative, source_file_path=filename)
631
+ if pxd:
632
+ return pxd
633
+ if is_relative:
634
+ return None # FIXME: error?
635
+ return self.context.find_pxd_file(module, source_file_path=filename)
636
+
637
+ @cached_method
638
+ def cimported_files(self, filename):
639
+ filename_root, filename_ext = os.path.splitext(filename)
640
+ if filename_ext in ('.pyx', '.py') and path_exists(filename_root + '.pxd'):
641
+ pxd_list = [filename_root + '.pxd']
642
+ elif filename_ext == '.oxy' and path_exists(filename_root + '.oxd'):
643
+ pxd_list = [filename_root + '.oxd']
644
+ else:
645
+ pxd_list = []
646
+ # Cimports generates all possible combinations package.module
647
+ # when imported as from package cimport module.
648
+ for module in self.cimports(filename):
649
+ if module[:7] == 'cython.' or module == 'cython':
650
+ continue
651
+ pxd_file = self.find_pxd(module, filename)
652
+ if pxd_file is not None:
653
+ pxd_list.append(pxd_file)
654
+ return tuple(pxd_list)
655
+
656
+ @cached_method
657
+ def immediate_dependencies(self, filename):
658
+ all_deps = {filename}
659
+ all_deps.update(self.cimported_files(filename))
660
+ all_deps.update(self.included_files(filename))
661
+ return all_deps
662
+
663
+ def all_dependencies(self, filename):
664
+ return self.transitive_merge(filename, self.immediate_dependencies, set.union)
665
+
666
+ @cached_method
667
+ def timestamp(self, filename):
668
+ return os.path.getmtime(filename)
669
+
670
+ def extract_timestamp(self, filename):
671
+ return self.timestamp(filename), filename
672
+
673
+ def newest_dependency(self, filename):
674
+ return max([self.extract_timestamp(f) for f in self.all_dependencies(filename)])
675
+
676
+ def distutils_info0(self, filename):
677
+ info = self.parse_dependencies(filename)[3]
678
+ kwds = info.values
679
+ cimports, externs, incdirs = self.cimports_externs_incdirs(filename)
680
+ basedir = os.getcwd()
681
+ # Add dependencies on "cdef extern from ..." files
682
+ if externs:
683
+ externs = _make_relative(externs, basedir)
684
+ if 'depends' in kwds:
685
+ kwds['depends'] = list(set(kwds['depends']).union(externs))
686
+ else:
687
+ kwds['depends'] = list(externs)
688
+ # Add include_dirs to ensure that the C compiler will find the
689
+ # "cdef extern from ..." files
690
+ if incdirs:
691
+ include_dirs = list(kwds.get('include_dirs', []))
692
+ for inc in _make_relative(incdirs, basedir):
693
+ if inc not in include_dirs:
694
+ include_dirs.append(inc)
695
+ kwds['include_dirs'] = include_dirs
696
+ return info
697
+
698
+ def distutils_info(self, filename, aliases=None, base=None):
699
+ return (self.transitive_merge(filename, self.distutils_info0, DistutilsInfo.merge)
700
+ .subs(aliases)
701
+ .merge(base))
702
+
703
+ def transitive_merge(self, node, extract, merge):
704
+ try:
705
+ seen = self._transitive_cache[extract, merge]
706
+ except KeyError:
707
+ seen = self._transitive_cache[extract, merge] = {}
708
+ return self.transitive_merge_helper(
709
+ node, extract, merge, seen, {}, self.cimported_files)[0]
710
+
711
+ def transitive_merge_helper(self, node, extract, merge, seen, stack, outgoing):
712
+ if node in seen:
713
+ return seen[node], None
714
+ deps = extract(node)
715
+ if node in stack:
716
+ return deps, node
717
+ try:
718
+ stack[node] = len(stack)
719
+ loop = None
720
+ for next in outgoing(node):
721
+ sub_deps, sub_loop = self.transitive_merge_helper(next, extract, merge, seen, stack, outgoing)
722
+ if sub_loop is not None:
723
+ if loop is not None and stack[loop] < stack[sub_loop]:
724
+ pass
725
+ else:
726
+ loop = sub_loop
727
+ deps = merge(deps, sub_deps)
728
+ if loop == node:
729
+ loop = None
730
+ if loop is None:
731
+ seen[node] = deps
732
+ return deps, loop
733
+ finally:
734
+ del stack[node]
735
+
736
+
737
+ _dep_tree = None
738
+
739
+ def create_dependency_tree(ctx=None, quiet=False):
740
+ global _dep_tree
741
+ if _dep_tree is None:
742
+ if ctx is None:
743
+ ctx = Context(["."], get_directive_defaults(),
744
+ options=CompilationOptions(default_options))
745
+ _dep_tree = DependencyTree(ctx, quiet=quiet)
746
+ return _dep_tree
747
+
748
+
749
+ # If this changes, change also docs/src/reference/compilation.rst
750
+ # which mentions this function
751
+ def default_create_extension(template, kwds):
752
+ if 'depends' in kwds:
753
+ include_dirs = kwds.get('include_dirs', []) + ["."]
754
+ depends = resolve_depends(kwds['depends'], include_dirs)
755
+ kwds['depends'] = sorted(set(depends + template.depends))
756
+
757
+ t = template.__class__
758
+ ext = t(**kwds)
759
+ if hasattr(template, "py_limited_api"):
760
+ ext.py_limited_api = template.py_limited_api
761
+ metadata = dict(distutils=kwds, module_name=kwds['name'])
762
+ return (ext, metadata)
763
+
764
+
765
+ # This may be useful for advanced users?
766
+ def create_extension_list(patterns, exclude=None, ctx=None, aliases=None, quiet=False, language=None,
767
+ exclude_failures=False):
768
+ if language is not None:
769
+ print('Warning: passing language={0!r} to cythonize() is deprecated. '
770
+ 'Instead, put "# distutils: language={0}" in your .pyx or .pxd file(s)'.format(language))
771
+ if exclude is None:
772
+ exclude = []
773
+ if patterns is None:
774
+ return [], {}
775
+ elif isinstance(patterns, str) or not isinstance(patterns, Iterable):
776
+ patterns = [patterns]
777
+
778
+ from distutils.extension import Extension
779
+ if 'setuptools' in sys.modules:
780
+ # Support setuptools Extension instances as well.
781
+ extension_classes = (
782
+ Extension, # should normally be the same as 'setuptools.extension._Extension'
783
+ sys.modules['setuptools.extension']._Extension,
784
+ sys.modules['setuptools'].Extension,
785
+ )
786
+ else:
787
+ extension_classes = (Extension,)
788
+
789
+ explicit_modules = {m.name for m in patterns if isinstance(m, extension_classes)}
790
+ deps = create_dependency_tree(ctx, quiet=quiet)
791
+ shared_utility_qualified_name = ctx.shared_utility_qualified_name
792
+
793
+ to_exclude = set()
794
+ if not isinstance(exclude, list):
795
+ exclude = [exclude]
796
+ for pattern in exclude:
797
+ to_exclude.update(map(os.path.abspath, extended_iglob(pattern)))
798
+
799
+ module_list = []
800
+ module_metadata = {}
801
+
802
+ # if no create_extension() function is defined, use a simple
803
+ # default function.
804
+ create_extension = ctx.options.create_extension or default_create_extension
805
+
806
+ seen = set()
807
+ for pattern in patterns:
808
+ if isinstance(pattern, str):
809
+ filepattern = pattern
810
+ template = Extension(pattern, []) # Fake Extension without sources
811
+ name = '*'
812
+ base = None
813
+ ext_language = language
814
+ elif isinstance(pattern, extension_classes):
815
+ cython_sources = [s for s in pattern.sources
816
+ if os.path.splitext(s)[1] in ('.py', '.pyx', '.oxy')]
817
+ template = pattern
818
+ name = template.name
819
+ base = DistutilsInfo(exn=template)
820
+ ext_language = None # do not override whatever the Extension says
821
+ if cython_sources:
822
+ filepattern = cython_sources[0]
823
+ if len(cython_sources) > 1:
824
+ print("Warning: Multiple cython sources found for extension '%s': %s\n"
825
+ "See https://cython.readthedocs.io/en/latest/src/userguide/sharing_declarations.html "
826
+ "for sharing declarations among Cython files." % (pattern.name, cython_sources))
827
+ elif shared_utility_qualified_name and pattern.name == shared_utility_qualified_name:
828
+ # This is the shared utility code file.
829
+ sources = pattern.sources or [
830
+ shared_utility_qualified_name.replace('.', os.sep) + ('.cpp' if pattern.language == 'c++' else '.c')]
831
+ m, _ = create_extension(pattern, dict(
832
+ name=shared_utility_qualified_name,
833
+ sources=sources,
834
+ language=pattern.language,
835
+ # shared utility code uses only parameters specified as argument of Extension() class
836
+ **base.values
837
+ ))
838
+ m.np_pythran = False
839
+ m.shared_utility_qualified_name = None
840
+ module_list.append(m)
841
+ continue
842
+ else:
843
+ # ignore non-cython modules
844
+ module_list.append(pattern)
845
+ continue
846
+ else:
847
+ msg = str("pattern is not of type str nor subclass of Extension (%s)"
848
+ " but of type %s and class %s" % (repr(Extension),
849
+ type(pattern),
850
+ pattern.__class__))
851
+ raise TypeError(msg)
852
+
853
+ for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
854
+ if os.path.abspath(file) in to_exclude:
855
+ continue
856
+ module_name = deps.fully_qualified_name(file)
857
+ if '*' in name:
858
+ if module_name in explicit_modules:
859
+ continue
860
+ elif name:
861
+ module_name = name
862
+
863
+ Utils.raise_error_if_module_name_forbidden(module_name)
864
+
865
+ if module_name not in seen:
866
+ try:
867
+ kwds = deps.distutils_info(file, aliases, base).values
868
+ except Exception:
869
+ if exclude_failures:
870
+ continue
871
+ raise
872
+ if base is not None:
873
+ for key, value in base.values.items():
874
+ if key not in kwds:
875
+ kwds[key] = value
876
+
877
+ kwds['name'] = module_name
878
+
879
+ sources = [file] + [m for m in template.sources if m != filepattern]
880
+ if 'sources' in kwds:
881
+ # allow users to add .c files etc.
882
+ for source in kwds['sources']:
883
+ if source not in sources:
884
+ sources.append(source)
885
+ kwds['sources'] = sources
886
+
887
+ if ext_language and 'language' not in kwds:
888
+ kwds['language'] = ext_language
889
+
890
+ np_pythran = kwds.pop('np_pythran', False)
891
+
892
+ # Create the new extension
893
+ m, metadata = create_extension(template, kwds)
894
+ m.np_pythran = np_pythran or getattr(m, 'np_pythran', False)
895
+ m.shared_utility_qualified_name = shared_utility_qualified_name
896
+ if m.np_pythran:
897
+ update_pythran_extension(m)
898
+ module_list.append(m)
899
+
900
+ # Store metadata (this will be written as JSON in the
901
+ # generated C file but otherwise has no purpose)
902
+ module_metadata[module_name] = metadata
903
+
904
+ if file not in m.sources:
905
+ # Old setuptools unconditionally replaces .pyx with .c/.cpp
906
+ target_file = os.path.splitext(file)[0] + ('.cpp' if m.language == 'c++' else '.c')
907
+ try:
908
+ m.sources.remove(target_file)
909
+ except ValueError:
910
+ # never seen this in the wild, but probably better to warn about this unexpected case
911
+ print("Warning: Cython source file not found in sources list, adding %s" % file)
912
+ m.sources.insert(0, file)
913
+ seen.add(name)
914
+ return module_list, module_metadata
915
+
916
+
917
+ # This is the user-exposed entry point.
918
+ def cythonize(module_list, exclude=None, nthreads=0, aliases=None, quiet=False, force=None, language=None,
919
+ exclude_failures=False, show_all_warnings=False, **options):
920
+ """
921
+ Compile a set of source modules into C/C++ files and return a list of distutils
922
+ Extension objects for them.
923
+
924
+ :param module_list: As module list, pass either a glob pattern, a list of glob
925
+ patterns or a list of Extension objects. The latter
926
+ allows you to configure the extensions separately
927
+ through the normal distutils options.
928
+ You can also pass Extension objects that have
929
+ glob patterns as their sources. Then, cythonize
930
+ will resolve the pattern and create a
931
+ copy of the Extension for every matching file.
932
+
933
+ :param exclude: When passing glob patterns as ``module_list``, you can exclude certain
934
+ module names explicitly by passing them into the ``exclude`` option.
935
+
936
+ :param nthreads: The number of concurrent builds for parallel compilation
937
+ (requires the ``multiprocessing`` module).
938
+
939
+ :param aliases: If you want to use compiler directives like ``# distutils: ...`` but
940
+ can only know at compile time (when running the ``setup.py``) which values
941
+ to use, you can use aliases and pass a dictionary mapping those aliases
942
+ to Python strings when calling :func:`cythonize`. As an example, say you
943
+ want to use the compiler
944
+ directive ``# distutils: include_dirs = ../static_libs/include/``
945
+ but this path isn't always fixed and you want to find it when running
946
+ the ``setup.py``. You can then do ``# distutils: include_dirs = MY_HEADERS``,
947
+ find the value of ``MY_HEADERS`` in the ``setup.py``, put it in a python
948
+ variable called ``foo`` as a string, and then call
949
+ ``cythonize(..., aliases={'MY_HEADERS': foo})``.
950
+
951
+ :param quiet: If True, Cython won't print error, warning, or status messages during the
952
+ compilation.
953
+
954
+ :param force: Forces the recompilation of the Cython modules, even if the timestamps
955
+ don't indicate that a recompilation is necessary.
956
+
957
+ :param language: To globally enable C++ mode, you can pass ``language='c++'``. Otherwise, this
958
+ will be determined at a per-file level based on compiler directives. This
959
+ affects only modules found based on file names. Extension instances passed
960
+ into :func:`cythonize` will not be changed. It is recommended to rather
961
+ use the compiler directive ``# distutils: language = c++`` than this option.
962
+
963
+ :param exclude_failures: For a broad 'try to compile' mode that ignores compilation
964
+ failures and simply excludes the failed extensions,
965
+ pass ``exclude_failures=True``. Note that this only
966
+ really makes sense for compiling ``.py`` files which can also
967
+ be used without compilation.
968
+
969
+ :param show_all_warnings: By default, not all Cython warnings are printed.
970
+ Set to true to show all warnings.
971
+
972
+ :param annotate: If ``True``, will produce a HTML file for each of the ``.pyx`` or ``.py``
973
+ files compiled. The HTML file gives an indication
974
+ of how much Python interaction there is in
975
+ each of the source code lines, compared to plain C code.
976
+ It also allows you to see the C/C++ code
977
+ generated for each line of Cython code. This report is invaluable when
978
+ optimizing a function for speed,
979
+ and for determining when to :ref:`release the GIL <nogil>`:
980
+ in general, a ``nogil`` block may contain only "white" code.
981
+ See examples in :ref:`determining_where_to_add_types` or
982
+ :ref:`primes`.
983
+
984
+
985
+ :param annotate-fullc: If ``True`` will produce a colorized HTML version of
986
+ the source which includes entire generated C/C++-code.
987
+
988
+
989
+ :param compiler_directives: Allow to set compiler directives in the ``setup.py`` like this:
990
+ ``compiler_directives={'embedsignature': True}``.
991
+ See :ref:`compiler-directives`.
992
+
993
+ :param depfile: produce depfiles for the sources if True.
994
+ :param cache: If ``True`` the cache enabled with default path. If the value is a path to a directory,
995
+ then the directory is used to cache generated ``.c``/``.cpp`` files. By default cache is disabled.
996
+ See :ref:`cython-cache`.
997
+ """
998
+ if exclude is None:
999
+ exclude = []
1000
+ if 'include_path' not in options:
1001
+ options['include_path'] = ['.']
1002
+ if 'common_utility_include_dir' in options:
1003
+ os.makedirs(options['common_utility_include_dir'], exist_ok=True)
1004
+
1005
+ depfile = options.pop('depfile', None)
1006
+
1007
+ if pythran is None:
1008
+ pythran_options = None
1009
+ else:
1010
+ pythran_options = CompilationOptions(**options)
1011
+ pythran_options.cplus = True
1012
+ pythran_options.np_pythran = True
1013
+
1014
+ if force is None:
1015
+ force = os.environ.get("CYTHON_FORCE_REGEN") == "1" # allow global overrides for build systems
1016
+
1017
+ c_options = CompilationOptions(**options)
1018
+ cpp_options = CompilationOptions(**options); cpp_options.cplus = True
1019
+ ctx = Context.from_options(c_options)
1020
+ options = c_options
1021
+ shared_utility_qualified_name = ctx.shared_utility_qualified_name
1022
+ module_list, module_metadata = create_extension_list(
1023
+ module_list,
1024
+ exclude=exclude,
1025
+ ctx=ctx,
1026
+ quiet=quiet,
1027
+ exclude_failures=exclude_failures,
1028
+ language=language,
1029
+ aliases=aliases)
1030
+
1031
+ deps = create_dependency_tree(ctx, quiet=quiet)
1032
+ build_dir = getattr(options, 'build_dir', None)
1033
+ if options.cache and not (options.annotate or Options.annotate):
1034
+ # cache is enabled when:
1035
+ # * options.cache is True (the default path to the cache base dir is used)
1036
+ # * options.cache is the explicit path to the cache base dir
1037
+ # * annotations are not generated
1038
+ cache_path = None if options.cache is True else options.cache
1039
+ cache = Cache(cache_path, getattr(options, 'cache_size', None))
1040
+ else:
1041
+ cache = None
1042
+
1043
+ def copy_to_build_dir(filepath, root=os.getcwd()):
1044
+ filepath_abs = os.path.abspath(filepath)
1045
+ if os.path.isabs(filepath):
1046
+ filepath = filepath_abs
1047
+ if filepath_abs.startswith(root):
1048
+ # distutil extension depends are relative to cwd
1049
+ mod_dir = join_path(build_dir,
1050
+ os.path.dirname(_relpath(filepath, root)))
1051
+ copy_once_if_newer(filepath_abs, mod_dir)
1052
+
1053
+ def file_in_build_dir(c_file):
1054
+ if not build_dir:
1055
+ return c_file
1056
+ if os.path.isabs(c_file):
1057
+ c_file = os.path.splitdrive(c_file)[1]
1058
+ c_file = c_file.split(os.sep, 1)[1]
1059
+ c_file = os.path.join(build_dir, c_file)
1060
+ dir = os.path.dirname(c_file)
1061
+ safe_makedirs_once(dir)
1062
+ return c_file
1063
+
1064
+ modules_by_cfile = collections.defaultdict(list)
1065
+ to_compile = []
1066
+ for m in module_list:
1067
+ if build_dir:
1068
+ for dep in m.depends:
1069
+ copy_to_build_dir(dep)
1070
+
1071
+ cy_sources = [
1072
+ source for source in m.sources
1073
+ if os.path.splitext(source)[1] in ('.pyx', '.py', '.oxy')]
1074
+ if len(cy_sources) == 1:
1075
+ # normal "special" case: believe the Extension module name to allow user overrides
1076
+ full_module_name = m.name
1077
+ else:
1078
+ # infer FQMN from source files
1079
+ full_module_name = None
1080
+
1081
+ np_pythran = getattr(m, 'np_pythran', False)
1082
+ py_limited_api = getattr(m, 'py_limited_api', False)
1083
+
1084
+ if np_pythran:
1085
+ options = pythran_options
1086
+ elif m.language == 'c++':
1087
+ options = cpp_options
1088
+ else:
1089
+ options = c_options
1090
+
1091
+ new_sources = []
1092
+ for source in m.sources:
1093
+ base, ext = os.path.splitext(source)
1094
+ if ext in ('.pyx', '.py', '.oxy'):
1095
+ c_file = base + ('.cpp' if m.language == 'c++' or np_pythran else '.c')
1096
+
1097
+ # setup for out of place build directory if enabled
1098
+ c_file = file_in_build_dir(c_file)
1099
+
1100
+ # write out the depfile, if requested
1101
+ if depfile:
1102
+ dependencies = deps.all_dependencies(source)
1103
+ write_depfile(c_file, source, dependencies)
1104
+
1105
+ # Missing files and those generated by other Cython versions should always be recreated.
1106
+ if Utils.file_generated_by_this_cython(c_file):
1107
+ c_timestamp = os.path.getmtime(c_file)
1108
+ else:
1109
+ c_timestamp = -1
1110
+
1111
+ # Priority goes first to modified files, second to direct
1112
+ # dependents, and finally to indirect dependents.
1113
+ if c_timestamp < deps.timestamp(source):
1114
+ dep_timestamp, dep = deps.timestamp(source), source
1115
+ priority = 0
1116
+ else:
1117
+ dep_timestamp, dep = deps.newest_dependency(source)
1118
+ priority = 2 - (dep in deps.immediate_dependencies(source))
1119
+ if force or c_timestamp < dep_timestamp:
1120
+ if not quiet and not force:
1121
+ if source == dep:
1122
+ print("Compiling %s because it changed." % Utils.decode_filename(source))
1123
+ else:
1124
+ print("Compiling %s because it depends on %s." % (
1125
+ Utils.decode_filename(source),
1126
+ Utils.decode_filename(dep),
1127
+ ))
1128
+ if not force and cache:
1129
+ fingerprint = cache.transitive_fingerprint(
1130
+ source, deps.all_dependencies(source), options,
1131
+ FingerprintFlags(m.language or 'c', py_limited_api, np_pythran)
1132
+ )
1133
+ else:
1134
+ fingerprint = None
1135
+ to_compile.append((
1136
+ priority, source, c_file, fingerprint, quiet,
1137
+ options, not exclude_failures, module_metadata.get(m.name),
1138
+ full_module_name, show_all_warnings))
1139
+ modules_by_cfile[c_file].append(m)
1140
+ elif shared_utility_qualified_name and m.name == shared_utility_qualified_name:
1141
+ # Generate shared utility code module now.
1142
+ c_file = file_in_build_dir(source)
1143
+ module_options = CompilationOptions(
1144
+ options, shared_c_file_path=c_file, shared_utility_qualified_name=None)
1145
+ if not Utils.is_cython_generated_file(c_file):
1146
+ print(f"Warning: Shared module source file is not a Cython file - not creating '{m.name}' as '{c_file}'")
1147
+ elif force or not Utils.file_generated_by_this_cython(c_file):
1148
+ from .SharedModule import generate_shared_module
1149
+ if not quiet:
1150
+ print(f"Generating shared module '{m.name}'")
1151
+ generate_shared_module(module_options)
1152
+ else:
1153
+ c_file = source
1154
+ if build_dir:
1155
+ copy_to_build_dir(source)
1156
+
1157
+ new_sources.append(c_file)
1158
+
1159
+ m.sources = new_sources
1160
+
1161
+ to_compile.sort()
1162
+ N = len(to_compile)
1163
+
1164
+ # Drop "priority" sorting component of "to_compile" entries
1165
+ # and add a simple progress indicator and the remaining arguments.
1166
+ build_progress_indicator = ("[{0:%d}/%d] " % (len(str(N)), N)).format
1167
+ to_compile = [
1168
+ task[1:] + (build_progress_indicator(i), cache)
1169
+ for i, task in enumerate(to_compile, 1)
1170
+ ]
1171
+
1172
+ if N <= 1:
1173
+ nthreads = 0
1174
+ try:
1175
+ from concurrent.futures import ProcessPoolExecutor
1176
+ except ImportError:
1177
+ nthreads = 0
1178
+
1179
+ if nthreads:
1180
+ with ProcessPoolExecutor(
1181
+ max_workers=nthreads,
1182
+ initializer=_init_multiprocessing_helper,
1183
+ ) as proc_pool:
1184
+ try:
1185
+ list(proc_pool.map(cythonize_one_helper, to_compile, chunksize=1))
1186
+ except KeyboardInterrupt:
1187
+ proc_pool.terminate_workers()
1188
+ proc_pool.shutdown(cancel_futures=True)
1189
+ raise
1190
+ else:
1191
+ for args in to_compile:
1192
+ cythonize_one(*args)
1193
+
1194
+ if exclude_failures:
1195
+ failed_modules = set()
1196
+ for c_file, modules in modules_by_cfile.items():
1197
+ if not os.path.exists(c_file):
1198
+ failed_modules.update(modules)
1199
+ elif os.path.getsize(c_file) < 200:
1200
+ f = open(c_file, 'r', encoding='iso8859-1')
1201
+ try:
1202
+ if f.read(len('#error ')) == '#error ':
1203
+ # dead compilation result
1204
+ failed_modules.update(modules)
1205
+ finally:
1206
+ f.close()
1207
+ if failed_modules:
1208
+ for module in failed_modules:
1209
+ module_list.remove(module)
1210
+ print("Failed compilations: %s" % ', '.join(sorted([
1211
+ module.name for module in failed_modules])))
1212
+
1213
+ if cache:
1214
+ cache.cleanup_cache()
1215
+
1216
+ # cythonize() is often followed by the (non-Python-buffered)
1217
+ # compiler output, flush now to avoid interleaving output.
1218
+ sys.stdout.flush()
1219
+ return module_list
1220
+
1221
+
1222
+ if os.environ.get('XML_RESULTS'):
1223
+ compile_result_dir = os.environ['XML_RESULTS']
1224
+ def record_results(func):
1225
+ def with_record(*args):
1226
+ t = time.time()
1227
+ success = False
1228
+ try:
1229
+ func(*args)
1230
+ success = True
1231
+ except Exception:
1232
+ # It's not obvious that we should really swallow the exception here,
1233
+ # rather than fail loudly after writing the XML result file,
1234
+ # but that's how it's currently implemented.
1235
+ pass
1236
+ finally:
1237
+ t = time.time() - t
1238
+ module = fully_qualified_name(args[0])
1239
+ name = "cythonize." + module
1240
+ failures = 1 - success
1241
+ with open(os.path.join(compile_result_dir, name + ".xml"), "w") as output:
1242
+ output.write(f"""
1243
+ <?xml version="1.0" ?>
1244
+ <testsuite name="{name}" errors="0" failures="{failures}" tests="1" time="{t}">
1245
+ <testcase classname="{name}" name="cythonize">
1246
+ {'' if success else 'failure'}
1247
+ </testcase>
1248
+ </testsuite>
1249
+ """.strip())
1250
+ return with_record
1251
+ else:
1252
+ def record_results(func):
1253
+ return func
1254
+
1255
+
1256
+ # TODO: Share context? Issue: pyx processing leaks into pxd module
1257
+ @record_results
1258
+ def cythonize_one(pyx_file, c_file,
1259
+ fingerprint=None, quiet=False, options=None,
1260
+ raise_on_failure=True, embedded_metadata=None,
1261
+ full_module_name=None, show_all_warnings=False,
1262
+ progress="", cache=None):
1263
+ from ..Compiler.Main import compile_single, default_options
1264
+ from ..Compiler.Errors import CompileError, PyrexError
1265
+
1266
+ if not quiet:
1267
+ if cache and fingerprint and cache.lookup_cache(c_file, fingerprint):
1268
+ print(f"{progress}Found compiled {pyx_file} in cache")
1269
+ else:
1270
+ print(f"{progress}Cythonizing {Utils.decode_filename(pyx_file)}")
1271
+ if options is None:
1272
+ options = CompilationOptions(default_options)
1273
+ options.output_file = c_file
1274
+ options.embedded_metadata = embedded_metadata
1275
+
1276
+ old_warning_level = Errors.LEVEL
1277
+ if show_all_warnings:
1278
+ Errors.LEVEL = 0
1279
+
1280
+ any_failures = 0
1281
+ try:
1282
+ result = compile_single(pyx_file, options, full_module_name=full_module_name, cache=cache, fingerprint=fingerprint)
1283
+ if result.num_errors > 0:
1284
+ any_failures = 1
1285
+ except (OSError, PyrexError) as e:
1286
+ sys.stderr.write('%s\n' % e)
1287
+ any_failures = 1
1288
+ # XXX
1289
+ import traceback
1290
+ traceback.print_exc()
1291
+ except Exception:
1292
+ if raise_on_failure:
1293
+ raise
1294
+ import traceback
1295
+ traceback.print_exc()
1296
+ any_failures = 1
1297
+ finally:
1298
+ if show_all_warnings:
1299
+ Errors.LEVEL = old_warning_level
1300
+
1301
+ if any_failures:
1302
+ if raise_on_failure:
1303
+ raise CompileError(None, pyx_file)
1304
+ elif os.path.exists(c_file):
1305
+ os.remove(c_file)
1306
+
1307
+
1308
+ def cythonize_one_helper(m):
1309
+ import traceback
1310
+ try:
1311
+ return cythonize_one(*m)
1312
+ except Exception:
1313
+ traceback.print_exc()
1314
+ raise
1315
+
1316
+
1317
+ def _init_multiprocessing_helper():
1318
+ # KeyboardInterrupt kills workers, so don't let them get it
1319
+ import signal
1320
+ signal.signal(signal.SIGINT, signal.SIG_IGN)