Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
shortening Python code
#1
to what extent and how do you guys go about shortening your Python code to make it fit in an 80 column terminal or virtual terminal window? is anyone here (still) using some form of a hardware terminal? if you use a virtual terminal how wide do you configure it? do you ever use the side-by-side approach to comparing or referencing code such that each virtual terminal gets about half the real physical screen width.

i find that when i limit my code width to 80 columns (or less) i end up with too many cases of code split to the next line or overly shortened comments, making it harder (for me) to read.

i run virtual terminals at 137x37 (character geometry in my 1920x1080 pixels) full screen or 174x45 if i need to push it. then i try to limit the code to a width of 128.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I use a ruler:
# ..|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|
Could write code to do it, but too lazy.
Reply
#3
(Oct-13-2022, 11:42 PM)Skaperen Wrote: how do you guys go about shortening your Python code
I don't usually have this problem because I tend to write short lines from the first draft and I keep them short. Also I use large fonts in my code editor, which encourages me to write short lines.

If you have this issue on a large scale, you should probably automatize the process by using a code formatter such as black or yapf.
Reply
#4
I always use black, isort, ssort to autoformat code and mypy to check types. In most cases, my code is not reformatted. But if I'm lazy, I even put no empty lines between functions. Saving the code with an IDE will run black automatically.
Larz60+ likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Black has become somewhat of a standard in Python that many use.
black doc Wrote:88 characters per line
Black defaults to 88 characters per line, which happens to be 10% over 80.
This number was found to produce significantly shorter files than sticking with 80 (the most popular),
or even 79 (used by the standard library).
I have set Black as default formatter in my editor VS Code.
Can test it out online here Black Playground
So it's uncompromising an will format eg data structure to what it means is the best way.
Eg dictionary.
mlb_team = {'Colorado' : 'Rockies','Boston': 'Red Sox','Minnesota':'Twins', 'Milwaukee': 'Brewers'}
After Black
mlb_team = {
    "Colorado": "Rockies",
    "Boston": "Red Sox",
    "Minnesota": "Twins",
    "Milwaukee": "Brewers",
}
Function with type hint.
from datetime import datetime
import os

def get_prices(file: os.PathLike, dates: list[datetime], price: int | float) -> list[float]:
    # To do
    ...
After Black.
from datetime import datetime
import os


def get_prices(
    file: os.PathLike,
    dates: list[datetime],
    price: int | float,
) -> list[float]:
    # To do
    ...
Larz60+ likes this post
Reply
#6
i already write lots of code with comma separated lists like function arguments split over lines and arranged vertically. but then, i end up commenting each argument or using long variable names. i do have many lines in a lot of code that are purely comment and end past column 100. i need to shorten my English and drop many of its needless words. but, i want to keep most of my comments.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
Out of curiosity, why do you have so many comments?
Reply
#8
You can also use textwrap to wrap the comments
#!/usr/bin/env python3
__doc__ = '''program wrapcomment.py
'''
__version__ = '0.0.1'
import argparse
import token
from tokenize import tokenize
import textwrap

def spit_comments(filename, width):
    with open(filename, 'rb') as ifh:
        for tok in tokenize(ifh.readline):
            if tok.type is token.COMMENT:
                s = textwrap.fill(tok.string, width=width)
                print(s)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description = """\
Applies textwrap to all the comments in the argument file
and print these comments to stdout.
        """)
    parser.add_argument('filename', metavar='PYFILE',
                        help='python program to scan.')
    parser.add_argument('-w', '--width', metavar='WIDTH', type=int, default=70, help='textwrap width')
    args = parser.parse_args()
    spit_comments(args.filename, width=args.width)
Reply
#9
black only verticalizes function calls for me if the function call is too long for the line width. does that seem right? i also see most string literals now having double quotes (").
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#10
(Oct-15-2022, 04:14 AM)ndc85430 Wrote: Out of curiosity, why do you have so many comments?

i like to go beyond what the code itself says and explain why or what the code enables (for example, explain obscure options that can be used in **kwargs). that, and i like to make it easier for beginners to understand what is generally going on. i write a lot of general use functions.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020