Sunday, April 20, 2025

Python Comments, DocStrings

If we need to explain part of code a little bit more (internally) we can use comments.

In Python, single-line comments start with hash(#) character.


#This is single-line comment

"""
We can also have explanation
on multiple lines.
Start and end them with 3 quotes.
"""

print("This will be printed") #This will not, bacause it's comment.

When we run it:


This will be printed
>>> 

Python Docstrings

What we see is Python function. Functions are like dedicated workers that will do specific job and nothing else.

In function, we can have short explanation (with 3 quotes aside). They are called "docstrings" because they are very specific "internal documentation" for that one function.

Create them immediately after function name.

For example, we can use them to generate automatic PDF documentation for all functions in our script. Or even, whole site can be based on docstrings, if our script have hundreds of functions.


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")

To access docstrings, just target that specific function, and add __doc__ to print command:


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")
    
print(first_function.__doc__)

Result:


 Brief explanation about func here 
>>> 

To use any function, just call it with: first_function() - don't forget parentheses. We need them because some functions can grab things in parentheses and do all types of further operations with data you provide.


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")
    
first_function()

Result:


Some Real Operations
>>> 

Ok, in next tutorial we will talk more about variables.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...