Share local namespace of the content file
This commit is contained in:
parent
934f96e77f
commit
365e658a1d
|
@ -46,15 +46,17 @@ def namespace_from(extension: type) -> dict:
|
|||
namespace[i] = extension[i]
|
||||
return namespace
|
||||
|
||||
def evaluate_this(content: str, global_ns: dict) -> str:
|
||||
def evaluate_this(content: str, global_ns: dict, local_ns: dict = {}) -> str:
|
||||
"""Finds some inline Python code in {braces} and evaluates it in-place.
|
||||
global_ns is a dictionary of globals that it can use. It's recommended to use
|
||||
namespace_from() to generate one.
|
||||
"""
|
||||
|
||||
return re.sub(r'\{([^\s}]+([^}]*[^\s}])?)\}', partial(evaluate, global_ns=global_ns), content)
|
||||
return re.sub(r'\{([^\s}]+([^}]*[^\s}])?)\}',
|
||||
partial(evaluate, global_ns=global_ns, local_ns=local_ns),
|
||||
content)
|
||||
|
||||
def evaluate(match: re.Match, global_ns: dict) -> str:
|
||||
def evaluate(match: re.Match, global_ns: dict, local_ns: dict) -> str:
|
||||
"""Callable for re.sub, returns value of the last Python expression line,
|
||||
executing all the other lines before.
|
||||
"""
|
||||
|
@ -64,7 +66,6 @@ def evaluate(match: re.Match, global_ns: dict) -> str:
|
|||
apis.environment = global_ns
|
||||
# we can't use 'return' in expressions
|
||||
# instead the last line will be evaluated and returned, the rest – executed
|
||||
local_ns = {}
|
||||
to_exec = '\n'.join(match[:-1])
|
||||
to_eval = match[-1]
|
||||
try:
|
||||
|
|
Reference in New Issue