Format Python source code, given as a string, for use with ``exec``. Use it like so:: exec(python_code(''' async def foo(): pass ''')) This allows to use newer syntactic constructs that'd cause SyntaxError on older Python versions.
(source)
| 89 | # Utility functions |
| 90 | |
| 91 | def python_code(source): |
| 92 | """Format Python source code, given as a string, for use with ``exec``. |
| 93 | |
| 94 | Use it like so:: |
| 95 | |
| 96 | exec(python_code(''' |
| 97 | async def foo(): |
| 98 | pass |
| 99 | ''')) |
| 100 | |
| 101 | This allows to use newer syntactic constructs that'd cause SyntaxError |
| 102 | on older Python versions. |
| 103 | """ |
| 104 | # (Whitespace shenanigans adapted from sphinx.utils.prepare_docstring) |
| 105 | |
| 106 | # remove excess whitespace from source code lines which will be there |
| 107 | # if the code was given as indented, multiline string |
| 108 | lines = source.expandtabs().splitlines() |
| 109 | margin = sys.maxsize |
| 110 | for line in lines: |
| 111 | code_len = len(line.strip()) |
| 112 | if code_len > 0: |
| 113 | indent = len(line) - code_len |
| 114 | margin = min(margin, indent) |
| 115 | if margin < sys.maxsize: |
| 116 | for i in range(len(lines)): |
| 117 | lines[i] = lines[i][margin:] |
| 118 | |
| 119 | # ensure there is an empty line at the end |
| 120 | if lines and lines[-1]: |
| 121 | lines.append('') |
| 122 | |
| 123 | return os.linesep.join(lines) |
no outgoing calls