How To Comment Set Of Lines In Python
Python Multi-line Comments: Your Two Best Options
Does Python support multi-line comments the way other languages exercise? What are your options for writing comment blocks in Python if you need them?

Nearly programming languages have syntax for cake comments that span multiple lines of text, like C or Java:
/* This is a block comment. It spans multiple lines. Nice, eh? */ int answer = 42 ;
How practice you write the same style of multiline annotate in Python? The short answer is: you can't—at least not in exactly the same way.
Python uses unlike conventions and syntax for block comments that span multiple lines. In this article you'll see some options for creating multiline comments in Python that actually work.
Option 1: Consecutive Single-line Comments
Your start choice for commenting out multiple lines of code in Python is to simply employ a #
single-line annotate on every line:
# This is a "cake comment" in Python, made # out of several single-line comments. # Pretty bully, eh? answer = 42
In my experience, most Python projects follow this style and Python's PEP 8 style guide also favors repeated single-line comments. So this is what I'd recommend that you use well-nigh of the time. This is also the but way to write "real" annotate blocks in Python that are ignored by the parser.
If it bothers you lot that Python doesn't back up proper multiline comments because you think information technology takes more effort to comment out multiple lines of code, here's a handy tip for you:
Most code editors have a shortcut for block commenting. In my Sublime Text development setup I simply select a couple of lines using shift
and the cursor keys (or the mouse) and and then I hit cmd + /
to comment them out all at one time.
This even works in reverse, that is, I tin select a block of single-line comments and when I hit the cmd + /
keyboard shortcut the whole block gets uncommented once more.
Other editors can practice this as well—Atom, VS Lawmaking, and even Notepad++ all have built-in shortcuts for cake commenting in Python. Managing your Python comments manually is a chore, and this editor characteristic can save you hours of your time.
Option ii: Using Multi-line Strings equally Comments
Some other option for writing "proper" multi-line comments in Python is to utilise multi-line strings with the """
syntax in creative ways. Here'due south an example:
""" This is a "block comment" in Python, made out of a mult-line string constant. This actually works quite well! """ answer = 42
As y'all tin run across, you lot can use triple-quoted strings to create something that resembles a multiline comment in Python. You lot just need to brand sure you indent the first """
correctly, otherwise you lot'll become a SyntaxError
. For example, if you'd similar to define a block annotate inside a function with this technique you accept to practice information technology similar this:
def add_stuff ( a , b ): result = a + b """ Now we return the result, wee! Hurray! I'm so excited I tin can't contain my joy to just i or 2 lines! """ return outcome
Merely keep in mind that this technique doesn't create "truthful" comments. This simply inserts a text constant that doesn't exercise anything. It'due south the same as inserting a regular unmarried-line string somewhere in your code and never accessing information technology.
Notwithstanding, such an orphaned cord abiding won't show upwards in the bytecode, effectively turning information technology into a multi-line comment. Here'due south proof that the unused cord won't appear in the CPython bytecode disassembly:
>>> import dis >>> dis . dis ( add_stuff ) 2 0 LOAD_FAST 0 ( a ) 2 LOAD_FAST 1 ( b ) 4 BINARY_ADD 6 STORE_FAST 2 ( upshot ) viii eight LOAD_FAST 2 ( issue ) 10 RETURN_VALUE
Notwithstanding, exist careful where you place these "comments" in the code. If the cord follows right after a office signature, a grade definition, or at the start of a module, information technology turns into a docstring which has a different meaning altogether in Python:
def add_stuff ( a , b ): """ This is now a function docstring associated with the part object and attainable every bit run-time metadata. """ event = a + b render outcome
Docstrings ("documentation strings") let y'all associate human-readable documentation with Python modules, functions, classes, and methods. They're different from source code comments:
A comment is removed by the parser, whereas a docstring ends up in the bytecode and is associated with the documented object. It can fifty-fifty be accessed programmatically at runtime.
Like I said before, the only fashion to get "true" multi-line comments in Python that get ignored past the parser is to utilize multiple #
single-line comments.
I'll admit I was slightly surprised to find this "simulated" block commenting style was endorsed past Guido van Rossum, the creator of Python:
"Python tip: You tin utilise multi-line strings as multi-line comments. Unless used equally docstrings, they generate no lawmaking! :-)" (Source)
Simply there you have it—in some cases using triple-quoted strings to make a comment cake might exist the right selection. Personally I'll try to avert them in product-set up code, but I occasionally utilize them when I'g working on a source file to jot downwards notes or to brand little advertizement-hoc to-do lists.
Multi-line Comments in Python – Central Takeaways
- Dissimilar other programming languages Python doesn't support multi-line annotate blocks out of the box.
- The recommended way to comment out multiple lines of code in Python is to use consecutive
#
single-line comments. This is the only way to get "truthful" source code comments that are removed by the Python parser. - You may consider using triple-quote
"""
strings to create something akin to multi-line comments in Python, just this isn't a perfect technique and your "comments" may plough into accidental docstrings.
Related Manufactures:
- The 4 Major Means to Do Cord Formatting in Python – Remember the Zen of Python and how there should be "one obvious way to do something in Python"? Yous might scratch your head when you observe out that at that place are *four* major ways to do string formatting in Python.
- Extending Python With C Libraries and the "ctypes" Module – An end-to-finish tutorial of how to extend your Python programs with libraries written in C, using the built-in "ctypes" module.
- Memoization in Python: How to Cache Office Results – Speed upward your Python programs with a powerful, however convenient, caching technique called "memoization."
- Python's enumerate() Role Demystified – How and why you lot should use the built-in enumerate function in Python to write cleaner and more Pythonic loops.
- Writing Python Command-Line Tools With Click – An in-depth tutorial on writing Python command-line (CLI) apps using the Click library for argument parsing and more.
- Interfacing Python and C: The CFFI Module – How to use Python's built-in CFFI module for interfacing Python with native libraries equally an alternative to the "ctypes" approach.
- Write More Pythonic Code by Applying the Things You Already Know – There's a mistake I oft make when I acquire new things almost Python… Here'due south how you tin avoid this pitfall and larn something about Python's "enumerate()" role at the same time.
- Working With File I/O in Python – Learn the basics of working with files in Python. How to read from files, how to write data to them, what file seeks are, and why files should exist closed.
- How to Reverse a String in Python – An overview of the iii main ways to reverse a Python cord: "slicing", contrary iteration, and the archetype in-place reversal algorithm. Also includes performance benchmarks.
- Mastering Click: Writing Advanced Python Control-Line Apps – How to improve your existing Click Python CLIs with advanced features like sub-commands, user input, parameter types, contexts, and more.
- Working with Random Numbers in Python – An overview for working with randomness in Python, using only functionality congenital into the standard library and CPython itself.
How To Comment Set Of Lines In Python,
Source: https://dbader.org/blog/python-multiline-comment
Posted by: johnsonbrin1966.blogspot.com
0 Response to "How To Comment Set Of Lines In Python"
Post a Comment