You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: crates/djc-safe-eval/README.md
+34Lines changed: 34 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -33,6 +33,7 @@ expression, but also collects metadata for the linter about:
33
33
34
34
1. What variables were used in the expression
35
35
2. What variables were introduced in the expression using walrus operator `x := 1`
36
+
3. What comments were found in the expression (including their positions and text)
36
37
37
38
## Usage
38
39
@@ -249,6 +250,39 @@ The entire python code must be a SINGLE [expression](https://docs.python.org/3/l
249
250
250
251
For simplicity we don't allow async features like async comprehensions.
251
252
253
+
### Comments
254
+
255
+
Python comments (`# ...`) are supported and are captured during parsing. Comments are preserved with their positions and text content, allowing linters and other tools to analyze them.
256
+
257
+
```python
258
+
compiled = safe_eval("x + 1 # Add one to x")
259
+
```
260
+
261
+
### Multiline expressions
262
+
263
+
Multiline expressions are supported. When an expression spans multiple lines, it is automatically wrapped in parentheses with newlines: `(\n{}\n)`. This wrapping serves two purposes:
264
+
265
+
1.**Enables multiline syntax**: In Python, when you're inside parentheses `(...)`, square brackets `[...]`, or curly braces `{...}`, Python ignores indentation and allows expressions to span multiple lines. This means you can write:
266
+
267
+
```python
268
+
[
269
+
1,
270
+
2,
271
+
3,
272
+
]
273
+
```
274
+
275
+
Without the wrapping, Python would require proper indentation.
276
+
277
+
2.**Allows trailing comments**: So we wrap the original expression in `(...)`. If used decided to add a comment after the expression, the comment would consume the closing `)`. Hence, we also add newlines so that `(` and `)` are on separate lines:
278
+
279
+
```
280
+
(2 + 2 # comment) ❌ Comment consumes the ')'
281
+
(\n2 + 2 # comment\n) ✅ Comment is on separate line
282
+
```
283
+
284
+
The wrapping is transparent to users - all token positions (variables, comments, etc.) are automatically adjusted to reference the original unwrapped source positions.
285
+
252
286
### Supported syntax
253
287
254
288
Almost anything that is a valid Python expression is allowed:
0 commit comments