Created
April 9, 2023 15:27
-
-
Save icaine/f374ee899ea4c51abc8736a7d8a12f0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def inline_func(code: str, globals_=None, locals_=None): | |
if globals_ is None: globals_ = globals() | |
if locals_ is None: locals_ = locals() | |
lines = code.splitlines(keepends=True) | |
indent = None | |
func_name = None | |
for i, line in enumerate(lines): | |
if indent is None: | |
if m := re.match(r'^(\s*)def\s+(\w+)', line): | |
indent, func_name = m.groups() | |
lines[i] = line.replace(indent, '', 1) | |
else: | |
lines[i] = line.replace(indent, '', 1) | |
code = ''.join(lines).strip() | |
exec(code, globals_, locals_) | |
return locals_[func_name] | |
assert list(map(inline_func( | |
''' | |
def f(x): | |
return (x + 1) ** 2 | |
''' | |
), | |
range(3) | |
)) == [1, 4, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment