-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwhere_clause.py
More file actions
47 lines (33 loc) · 1.64 KB
/
where_clause.py
File metadata and controls
47 lines (33 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
''' from __experimental__ import where_clause
shows how one could use `where` as a keyword to introduce a code
block that would be ignored by Python. The idea was to use this as
a _pythonic_ notation as an alternative for the optional type hinting described
in PEP484. **This idea has been rejected** as it would not have
been compatible with some older versions of Python, unlike the
approach that has been accepted.
https://www.python.org/dev/peps/pep-0484/#other-forms-of-new-syntax
:warning: This transformation **cannot** be used in the console.
For more details, please see two of my recent blog posts:
https://aroberge.blogspot.ca/2015/12/revisiting-old-friend-yet-again.html
https://aroberge.blogspot.ca/2015/01/type-hinting-in-python-focus-on.html
I first suggested this idea more than 12 years ago! ;-)
https://aroberge.blogspot.ca/2005/01/where-keyword-and-python-as-pseudo.html
'''
from io import StringIO
import tokenize
NO_CONSOLE = '\nWarning: where_clause is not allowed in the console.\n'
def transform_source(text):
'''removes a "where" clause which is identified by the use of "where"
as an identifier and ends at the first DEDENT (i.e. decrease in indentation)'''
toks = tokenize.generate_tokens(StringIO(text).readline)
result = []
where_clause = False
for toktype, tokvalue, _, _, _ in toks:
if toktype == tokenize.NAME and tokvalue == "where":
where_clause = True
elif where_clause and toktype == tokenize.DEDENT:
where_clause = False
continue
if not where_clause:
result.append((toktype, tokvalue))
return tokenize.untokenize(result)