how to detect comment in source code file ?

V

vnkumbhani

how works python interpreter for finding comment ?
if possible find nested comment ?
 
P

Paul Rudin

Ben Finney said:
It works as specified in the language reference. In particular, see


Python's comments are line-end comments only. The syntax does not allow
multi-line nor nested comments.

Although you can use unbound multi-line strings as a kind of
comment. But its often better to make the strings into doc strings
proper.
 
S

Steven D'Aprano

It works as specified in the language reference. In particular, see


Python's comments are line-end comments only. The syntax does not allow
multi-line nor nested comments.

While that's technically true, you can use bare strings as de facto
comments. The compiler drops any bare strings it sees, so one can nest
pseudo-comments like this:


do_this()
"""
do_that()
do_something() # Make the widget work correctly.
'''
for x in range(5):
do_something_else()
'''
do_something_different()
"""


In the above, everything except do_this() is commented out by being
turned into a string.
 
D

Dennis Lee Bieber

how works python interpreter for finding comment ?
if possible find nested comment ?

Python does not have "nested comment". Comments begin at any #
character that is not inside a string (something inside ' or " pairs).
 
V

Vincent Vande Vyvre

Le 04/09/2013 08:05, (e-mail address removed) a écrit :
how works python interpreter for finding comment ?
if possible find nested comment ?
If you need to find it yourself, you can use the module tokenize.

ex.:
---------------------------------------------------------------
import tokenize
from StringIO import StringIO

script = "# importing comment\nfrom foo import baz"\
"if baz.vers < 2:\n AUTO = False # Retrocompatibility"

def find_comment():
print script
cmt = tokenize.COMMENT
tokens = tokenize.generate_tokens(StringIO(script).readline)
for typ, _, begin, _, _ in tokens:
if typ == cmt:
print 'Find comment line %s at column %s' % begin

find_comment()
 
P

Piet van Oostrum

Dennis Lee Bieber said:
Python does not have "nested comment". Comments begin at any #
character that is not inside a string (something inside ' or " pairs).

You could consider this a kind of nested comment :)

# if condition:
# # calculate the amount
# amount = sum(parts)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top