Comments (8)
Is the linked pull request what you need?
from asttokens.
Looks promising!
from asttokens.
I changed it actually, and committed to master, with some tests. Turns out there is no need for include_extra
parameter, it should just always use True. So if you are looking for tokenize.COMMENT
, it will now find it, and if you were looking for a regular token, it works the same as before. So the interface is the same, but your use case is fixed.
I'm closing, but let me know if you still have any issues with this.
from asttokens.
Thanks - any idea when the new version will be available via pip?
from asttokens.
Just published.
from asttokens.
Might have found a problem - or maybe its the way I'm using the library. When I scan for comments on a node, the next comment in the entire source code is found - regardless of how far away it is. I need to find comments only on the line that the node is part of.
Here is the repro of the weird behaviour:
import ast
import asttokens
import tokenize
from textwrap import dedent
src = dedent("""
def hello():
x = 5
there()
def there():
return 999 # my silly comment
hello() # call it
there()
""")
class RecursiveVisitor(ast.NodeVisitor):
""" example recursive visitor """
def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self,node):
self.dump_line_and_comment(node)
func(self,node)
for child in ast.iter_child_nodes(node):
self.visit(child)
return wrapper
def dump_line_and_comment(self, node):
comment = atok.find_token(node.first_token, tokenize.COMMENT)
print(f'On line "{node.first_token.line.strip():20s}" find_token found "{comment}"')
@recursive
def visit_Assign(self,node):
""" visit a Assign node and visits it recursively"""
@recursive
def visit_BinOp(self, node):
""" visit a BinOp node and visits it recursively"""
@recursive
def visit_Call(self,node):
""" visit a Call node and visits it recursively"""
@recursive
def visit_Lambda(self,node):
""" visit a Function node """
@recursive
def visit_FunctionDef(self,node):
""" visit a Function node and visits it recursively"""
atok = asttokens.ASTTokens(src, parse=True)
tree = atok.tree
visitor = RecursiveVisitor()
visitor.visit(tree)
Gives me:
On line "def hello(): " find_token found "COMMENT:'# my silly comment'"
On line "x = 5 " find_token found "COMMENT:'# my silly comment'"
On line "there() " find_token found "COMMENT:'# my silly comment'"
On line "def there(): " find_token found "COMMENT:'# my silly comment'"
On line "hello() # call it " find_token found "COMMENT:'# call it'"
On line "there() " find_token found "ENDMARKER:''"
from asttokens.
That's not a problem with this module, it's just not a feature of it: find_token
finds the next matching token regardless of the line. But line breaks themselves introduce tokens, so you can write a helper to find the next comment on the same line as a given token, like so:
def find_line_comment(atok, start_token):
t = start_token
while t.type not in (tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE, token.ENDMARKER):
t = atok.next_token(t, include_extra=True)
return t if t.type == tokenize.COMMENT else None
from asttokens.
Thanks - that helper routine works great. A slight tweak I made is to either return the comment string or an empty string:
def find_line_comment(start_token):
t = start_token
while t.type not in (tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE, tokenize.ENDMARKER):
t = self.atok.next_token(t, include_extra=True)
return t.string if t.type == tokenize.COMMENT else ''
comment = find_line_comment(node.first_token)
P.S. My old hack approach was not very 'token' based and for the curious, was simply:
line = node.first_token.line
comment_i = line.find('#')
comment = line[comment_i:].strip() if comment_i != -1 else ''
from asttokens.
Related Issues (20)
- DeprecationWarning: The 'astroid.node_classes' module is deprecated HOT 5
- ASTText astroid support HOT 1
- IndexError in asttokens.ASTTokens HOT 2
- Timelines around support for legacy Python HOT 2
- Replace deprecated imp module with importlib HOT 2
- Compatibility with Python 3.12 and unreleased astroid 3.0.0 HOT 1
- Get node from token? HOT 2
- Official support for 3.9 and maybe 3.10
- 2.0.5 tag missing HOT 2
- Test failure with py3.8 and astroid-2.6+: tests/test_astroid.py::TestAstroid::test_slices - AssertionError: Items in the first set but not the second: HOT 3
- Comma misannotation bug HOT 2
- Fix travis build
- Test new syntax in 3.10 HOT 2
- 2.0.5: pytest is failing in few `astroid` units HOT 15
- `asttokens` 2.0.6 has undeclared dependency on `astroid` HOT 8
- Followup to astroid import fix
- mypy reports `error: Name "asttokens.ASTTokens" is not defined` HOT 4
- Support for constructing around a list of existing tokens HOT 6
- Docs outdated HOT 3
- Consider a clearer optional-functionality API HOT 15
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from asttokens.