Related
How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.
'''
This is a multiline
comment.
'''
(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)
Guido van Rossum (creator of Python) tweeted this as a "pro tip".
However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:
# This is a multiline
# comment.
...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
To protect against link decay, here is the content of Guido van Rossum's tweet:
#BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
From the accepted answer...
You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.
This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.
If you try to run this code...
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
You'll get either...
ValueError: invalid \x escape
...on Python 2.x or...
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...on Python 3.x.
The only way to do multi-line comments which are ignored by the parser is...
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()
In Python 2.7 the multiline comment is:
"""
This is a
multilline comment
"""
In case you are inside a class you should tab it properly.
For example:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.
If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.
There is no such feature as a multi-line comment. # is the only way to comment a single line of code.
Many of you answered ''' a comment ''' this as their solution.
It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.
Check the official documentation here
I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.
If you put a comment in
"""
long comment here
"""
in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use
# Long comment
# here.
If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.
If you don’t want to use plugins like the above you can use search and replace like
:.,.+1s/^/# /g
This will replace the first character on the current and next line with #.
Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.
macOS: Select code-block and then ⌘+/
Windows: Select code-block and then Ctrl+/
Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.
Here is an example:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
I would advise against using """ for multi line comments!
Here is a simple example to highlight what might be considered an unexpected behavior:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
Now have a look at the output:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.
If you want to comment multiple lines do so according to PEP 8 guidelines:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
Output:
I am a string
clearly I am also a string
Well, you can try this (when running the quoted, the input to the first question should quoted with '):
"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")
"""
a = input()
print(a)
print(a*5)
Whatever enclosed between """ will be commented.
If you are looking for single-line comments then it's #.
Multiline comment in Python:
For me, both ''' and """ worked.
Example:
a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)
Example:
a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign
print("Hello World") # printing
If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign
# single line comment
To write comments longer than 1 line, you use 3 quotes
"""
This is a comment
written in
more than just one line
"""
On Python 2.7.13:
Single:
"A sample single line comment "
Multiline:
"""
A sample
multiline comment
on PyCharm
"""
The inline comments in Python starts with a hash character.
hello = "Hello!" # This is an inline comment
print(hello)
Hello!
Note that a hash character within a string literal is just a hash character.
dial = "Dial #100 to make an emergency call."
print(dial)
Dial #100 to make an emergency call.
A hash character can also be used for single or multiple lines comments.
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
Hello
World
Enclose the text with triple double quotes to support docstring.
def say_hello(name):
"""
This is docstring comment and
it's support multi line.
:param name it's your name
:type name str
"""
return "Hello " + name + '!'
print(say_hello("John"))
Hello John!
Enclose the text with triple single quotes for block comments.
'''
I don't care the parameters and
docstrings here.
'''
Using PyCharm IDE.
You can comment and uncomment lines of code using Ctrl+/.
Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts).
Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print("Loop ended.")
Select all lines then press Ctrl + /
# n = 5
# while n > 0:
# n -= 1
# if n == 2:
# break
# print(n)
# print("Loop ended.")
Yes, it is fine to use both:
'''
Comments
'''
and
"""
Comments
"""
But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.
Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.
I am using Anaconda Spyder and it has:
Ctrl + 1 - Comment/uncomment
Ctrl + 4 - Comment a block of code
Ctrl + 5 - Uncomment a block of code
It would comment/uncomment a single/multi line/s of code with #.
I find it the easiest.
For example, a block comment:
# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
Yes, you can simply use
'''
Multiline!
(?)
'''
or
"""
Hello
World!
"""
BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:
# This is also
# a multiline comment.
For this one, you can select the text you want to comment and press Ctrl / (or ⌘ /), in PyCharm and VS Code.
But you can edit them. For example, you can change the shortcut from Ctrl /
to Ctrl Shift C.
WARNING!
Be careful, don't overwrite other shortcuts!
Comments have to be correctly indented!
Hope this answer helped. Good luck next time when you'll write other answers!
This can be done in Vim text editor.
Go to the beginning of the first line in the comment area.
Press Ctrl+V to enter the visual mode.
Use arrow keys to select all the lines to be commented.
Press Shift+I.
Press # (or Shift+3).
Press Esc.
For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:
# This is comment 1
# This is comment 2
# This is comment 3
For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax
Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.
'''
This is
multiline
comment
'''
Also, mention that you can access docstring by a class object like this
myobj.__doc__
A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.
A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.
Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.
For single line you can use Shift + #.
You can use the following. This is called DockString.
def my_function(arg1):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print my_function.__doc__
in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments.
in mac: it should be comment + /
I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
It is obvious to any other programmer this is a comment. It's self-descriptive.
It compiles
It doesn't show up as a doc comment in help()
It can be at the top of the module if desired
It can be automated with a macro.
[The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.
Cons
It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.
Here's an attempt at the VS Code macro, although I haven't tested it yet:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}
I have already read this: Why doesn't Python have multiline comments?
So in my IDLE , I wrote a comment:
Hello#World
Anything after the d of world is also a part of the comment.In c++ , I am aware of a way to close the comment like:
/*Mycomment*/
Is there a way to end a comment in Python?
NOTE: I would not prefer not to use the triple quotes.
You've already read there are no multiline comments, only single line. Comments cause Python to ignore everything until the end of the line. You "close" them with a newline!
I don't particularly like it, but some people use multiline strings as comments. Since you're just throwing away the value, you can approximate a comment this way. The only time it's really doing anything is when it's the first line in a function or class block, in which case it is treated as a docstring.
Also, this may be more of a shell scripting convention, but what's so bad about using multiple single line comments?
#####################################################################
# It is perfectly fine and natural to write "multi-line" comments #
# using multiple single line comments. Some people even draw boxes #
# with them! #
#####################################################################
You can't close a comment in python other than by ending the line.
There are number of things you can do to provide a comment in the middle of an expression or statement, if that's really what you want to do.
First, with functions you annotate arguments -- an annotation can be anything:
def func(arg0: "arg0 should be a str or int", arg1: (tuple, list)):
...
If you start an expression with ( the expression continues beyond newlines until a matching ) is encountered. Thus
assert (
str
# some comment
.
# another comment
join
) == str.join
You can emulate comments by using strings. They are not exactly comments, since they execute, but they don't return anything.
print("Hello", end = " ");"Comment";print("World!")
if you start with triple quotes, end with triple quotes
How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.
'''
This is a multiline
comment.
'''
(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)
Guido van Rossum (creator of Python) tweeted this as a "pro tip".
However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:
# This is a multiline
# comment.
...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
To protect against link decay, here is the content of Guido van Rossum's tweet:
#BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
From the accepted answer...
You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.
This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.
If you try to run this code...
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
You'll get either...
ValueError: invalid \x escape
...on Python 2.x or...
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...on Python 3.x.
The only way to do multi-line comments which are ignored by the parser is...
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()
In Python 2.7 the multiline comment is:
"""
This is a
multilline comment
"""
In case you are inside a class you should tab it properly.
For example:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.
If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.
There is no such feature as a multi-line comment. # is the only way to comment a single line of code.
Many of you answered ''' a comment ''' this as their solution.
It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.
Check the official documentation here
I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.
If you put a comment in
"""
long comment here
"""
in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use
# Long comment
# here.
If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.
If you don’t want to use plugins like the above you can use search and replace like
:.,.+1s/^/# /g
This will replace the first character on the current and next line with #.
Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.
macOS: Select code-block and then ⌘+/
Windows: Select code-block and then Ctrl+/
Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.
Here is an example:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
I would advise against using """ for multi line comments!
Here is a simple example to highlight what might be considered an unexpected behavior:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
Now have a look at the output:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.
If you want to comment multiple lines do so according to PEP 8 guidelines:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
Output:
I am a string
clearly I am also a string
Well, you can try this (when running the quoted, the input to the first question should quoted with '):
"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")
"""
a = input()
print(a)
print(a*5)
Whatever enclosed between """ will be commented.
If you are looking for single-line comments then it's #.
Multiline comment in Python:
For me, both ''' and """ worked.
Example:
a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)
Example:
a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign
print("Hello World") # printing
If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign
# single line comment
To write comments longer than 1 line, you use 3 quotes
"""
This is a comment
written in
more than just one line
"""
On Python 2.7.13:
Single:
"A sample single line comment "
Multiline:
"""
A sample
multiline comment
on PyCharm
"""
The inline comments in Python starts with a hash character.
hello = "Hello!" # This is an inline comment
print(hello)
Hello!
Note that a hash character within a string literal is just a hash character.
dial = "Dial #100 to make an emergency call."
print(dial)
Dial #100 to make an emergency call.
A hash character can also be used for single or multiple lines comments.
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
Hello
World
Enclose the text with triple double quotes to support docstring.
def say_hello(name):
"""
This is docstring comment and
it's support multi line.
:param name it's your name
:type name str
"""
return "Hello " + name + '!'
print(say_hello("John"))
Hello John!
Enclose the text with triple single quotes for block comments.
'''
I don't care the parameters and
docstrings here.
'''
Using PyCharm IDE.
You can comment and uncomment lines of code using Ctrl+/.
Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts).
Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print("Loop ended.")
Select all lines then press Ctrl + /
# n = 5
# while n > 0:
# n -= 1
# if n == 2:
# break
# print(n)
# print("Loop ended.")
Yes, it is fine to use both:
'''
Comments
'''
and
"""
Comments
"""
But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.
Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.
I am using Anaconda Spyder and it has:
Ctrl + 1 - Comment/uncomment
Ctrl + 4 - Comment a block of code
Ctrl + 5 - Uncomment a block of code
It would comment/uncomment a single/multi line/s of code with #.
I find it the easiest.
For example, a block comment:
# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
Yes, you can simply use
'''
Multiline!
(?)
'''
or
"""
Hello
World!
"""
BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:
# This is also
# a multiline comment.
For this one, you can select the text you want to comment and press Ctrl / (or ⌘ /), in PyCharm and VS Code.
But you can edit them. For example, you can change the shortcut from Ctrl /
to Ctrl Shift C.
WARNING!
Be careful, don't overwrite other shortcuts!
Comments have to be correctly indented!
Hope this answer helped. Good luck next time when you'll write other answers!
This can be done in Vim text editor.
Go to the beginning of the first line in the comment area.
Press Ctrl+V to enter the visual mode.
Use arrow keys to select all the lines to be commented.
Press Shift+I.
Press # (or Shift+3).
Press Esc.
For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:
# This is comment 1
# This is comment 2
# This is comment 3
For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax
Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.
'''
This is
multiline
comment
'''
Also, mention that you can access docstring by a class object like this
myobj.__doc__
A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.
A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.
Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.
For single line you can use Shift + #.
You can use the following. This is called DockString.
def my_function(arg1):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print my_function.__doc__
in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments.
in mac: it should be comment + /
I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
It is obvious to any other programmer this is a comment. It's self-descriptive.
It compiles
It doesn't show up as a doc comment in help()
It can be at the top of the module if desired
It can be automated with a macro.
[The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.
Cons
It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.
Here's an attempt at the VS Code macro, although I haven't tested it yet:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}
Which is preferred ("." indicating whitespace)?
A)
def foo():
x = 1
y = 2
....
if True:
bar()
B)
def foo():
x = 1
y = 2
if True:
bar()
My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?
If you use A, you could copy paste your block in python shell, B will get unexpected indentation error.
The PEP 8 does not seem to be clear on this issue, although the statements about "blank lines" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will successfully interpret the code in either case that this doesn't really matter, and trying to enforce it would be a lot of work for very little gain. I suppose if you are very adamantly in favor of one or the other you could automatically convert the one to the other. Trying to fix all such lines manually, though, would be a huge undertaking and really not worth the effort, IMHO.
Adding proper indentation to blank lines (style A in the question) vastly improves code readability with display whitespace enabled because it makes it easier to see whether code after a blank line is part of the same indentation block or not.
For a language like Python, where there is no end statement or close bracket, I'm surprised this is not part of PEP. Editing Python with display whitespace on is strongly recommended, to avoid both trailing whitespace and mixed indentation.
Compare reading the following:
A)
def foo():
....x = 1
....y = 2
....
....if True:
........bar()
B)
def foo():
....x = 1
....y = 2
....if True:
........bar()
In A, it is far clearer that the last two lines are part of foo. This is even more useful at higher indentation levels.
That empty line belongs to foo(), so I would consider A to be the most natural. But I guess it's just a matter of opinion.
TextMate breaks block collapsing if you use B, and I prefer A anyway since it's more "logical".
My experience in open-source development is that one should never leave whitespace inside blank lines. Also one should never leave trailing white-space.
It's a matter of coding etiquette.
I wouldn't necessarily call the first example "broken", because I know some people hate it when the cursor "jumps back" when moving the cursor up or down in code. E.g. Visual Studio (at least 2008) automatically prevents this from happening without using any whitespace characters on those lines.
B is preferred - i.e. no indentation. PEP 8 says:
Avoid trailing whitespace anywhere. Because it's usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don't preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
Emacs does B) for me, but I really don't think it matters. A) means that you can add in a line at the correct indentation without any tabbing.
vi implicitly discourages the behaviour in A because the {/} navigations no longer work as expected. git explicitly discourages it by highlighting it in red when you run git diff. I would also argue that if a line contains spaces it is not a blank line.
For that reason I strongly prefer B. There is nothing worse than expecting to skip six or so lines up with the { motion and ending up at the top of a class def.
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
There's a solution to your problem that is distributed with python itself. pindent.py, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to grab it from svn.python.org if you are running on Linux or OSX.
It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:
pindent.py -c myfile.py
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
Where the original myfile.py was:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
else:
print 'oops!'
You can also use pindent.py -r to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.
For example, running pindent.py -r myfile.py will convert the following code in myfile.py into the same properly indented (and also commented) code as produced by the pindent.py -c example above:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.
I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?
I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be.
In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you.
I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to.
Edit: Also, as noted by John Millikin There is also PyBraces Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use)
Edit 2: I've just reported this to the python bug tracker
Although I am not blind, I have heard good things about Emacspeak. They've had a Python mode since their 8.0 release in 1998 (they seem to be up to release 28.0!). Definitely worth checking out.
You should be able to configure your editor to speak the tabs and spaces -- I know it's possible to display whitespace in most editors, so there must be an accessibility option somewhere to speak them.
Failing that, there is pybraces, which was written as a practical joke but might actually be useful to you with a bit of work.
If you're on Windows, I strongly recommend you take a look at EdSharp from:
http://empowermentzone.com/EdSharp.htm
It supports all of the leading Windows screenreaders, it can be configured to speak the indentation levels of code, or it has a built in utility called PyBrace that can convert to and from braces syntax if you want to do that instead, and it supports all kinds of other features programmers have come to expect in our text editors. I've been using it for years, for everything from PHP to JavaScript to HTML to Python, and I love it.
All of these "no you can't" types of answers are really annoying. Of course you can.
It's a hack, but you can do it.
http://timhatch.com/projects/pybraces/
uses a custom encoding to convert braces to indented blocks before handing it off to the interpreter.
As an aside, and as someone new to python - I don't accept the reasoning behind not even allowing braces/generic block delimiters ... apart from that being the preference of the python devs. Braces at least won't get eaten accidentally if you're doing some automatic processing of your code or working in an editor that doesn't understand that white space is important. If you're generating code automatically, it's handy to not have to keep track of indent levels. If you want to use python to do a perl-esque one-liner, you're automatically crippled. If nothing else, just as a safeguard. What if your 1000 line python program gets all of its tabs eaten? You're going to go line-by-line and figure out where the indenting should be?
Asking about it will invariably get a tongue-in-cheek response like "just do 'from __ future __ import braces'", "configure your IDE correctly", "it's better anyway so get used to it" ...
I see their point, but hey, if i wanted to, i could put a semicolon after every single line. So I don't understand why everyone is so adamant about the braces thing. If you need your language to force you to indent properly, you're not doing it right in the first place.
Just my 2c - I'm going to use braces anyway.
I appreciate your problem, but think you are specifying the implementation instead of the problem you need solved. Instead of converting to braces, how about working on a way for your screen reader to tell you the indentation level?
For example, some people have worked on vim syntax coloring to represent python indentation levels. Perhaps a modified syntax coloring could produce something your screen reader would read?
Searching an accessible Python IDE, found this and decided to answer.
Under Windows with JAWS:
Go to Settings Center by pressing JawsKey+6 (on the number row above the letters) in your favorite text editor. If JAWS prompts to create a new configuration file, agree.
In the search field, type "indent"
There will be only one result: "Say indent characters". Turn this on.
Enjoy!
The only thing that is frustrating for us is that we can't enjoy code examples on websites (since indent speaking in browsers is not too comfortable — it generates superfluous speech).
Happy coding from another Python beginner).
I use eclipse with the pydev extensions since it's an IDE I have a lot of experience with. I also appreciate the smart indentation it offers for coding if statements, loops, etc. I have configured the pindent.py script as an external tool that I can run on the currently focused python module which makes my life easier so I can see what is closed where with out having to constantly check indentation.
There are various answers explaining how to do this. But I would recommend not taking this route. While you could use a script to do the conversion, it would make it hard to work on a team project.
My recommendation would be to configure your screen reader to announce the tabs. This isn't as annoying as it sounds, since it would only say "indent 5" rather than "tab tab tab tab tab". Furthermore, the indentation would only be read whenever it changed, so you could go through an entire block of code without hearing the indentation level. In this way hearing the indentation is no more verbose than hearing the braces.
As I don't know which operating system or screen reader you use I unfortunately can't give the exact steps for achieving this.
Edsger Dijkstra used if ~ fi and do ~ od in his "Guarded Command Language", these appear to originate from the Algol68. There were also some example python guarded blocks used in RosettaCode.org.
fi = od = yrt = end = lambda object: None;
class MyClass(object):
def myfunction(self, arg1, arg2):
for i in range(arg1) :# do
if i > 5 :# then
print i
fi
od # or end(i) #
end(myfunction)
end(MyClass)
Whitespace mangled python code can be unambiguously unmangled and reindented if one uses
guarded blocks if/fi, do/od & try/yrt together with semicolons ";" to separate statements. Excellent for unambiguous magazine listings or cut/pasting from web pages.
It should be easy enough to write a short python program to insert/remove the guard blocks and semicolons.