Skip to content

Instantly share code, notes, and snippets.

@MohammadHosseinGhorbani
Created August 7, 2024 15:31
Show Gist options
  • Save MohammadHosseinGhorbani/b22231ac6207c31a6a1f44bcf6f996a7 to your computer and use it in GitHub Desktop.
Save MohammadHosseinGhorbani/b22231ac6207c31a6a1f44bcf6f996a7 to your computer and use it in GitHub Desktop.
Python Evaluation in text like Django Templates
### Example 1:
>>> format_eval("Hello {{ 'world'.upper() }}")
'Hello WORLD'
### Example 2:
>>> import requests
>>> format_eval("Request to Google: Code {{ requests.get('https://google.com').status_code) }}")
'Request to Google: Code SyntaxError'
>>> format_eval("Request to Google: Code {{ requests.get('https://google.com').status_code }}")
'Request to Google: Code 200'
### Example 3:
>>> print(format_eval("""Your Username: {{ (username := 'MohammadHosseinGhorbani') }}
... Is Valid: {{ not username.startswith('_') }}"""))
Your Username: MohammadHosseinGhorbani
Is Valid: True
def format_eval(text: str):
while '{{' in text and '}}' in text:
start = text.index('{{')
end = text.index('}}')
try:
text = text.replace(text[start:end+2], str(eval(text[start+2:end])))
except Exception as e:
text = text.replace(text[start:end+2], repr(type(e)())[:-2])
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment