Ricky Wilson
Ricky Wilson

Reputation: 3359

How should I shorten this line of Python code?

Here is the line that needs to be shortened.

tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))

Upvotes: 4

Views: 2126

Answers (2)

3Doubloons
3Doubloons

Reputation: 2106

You can use a feature of Python called Implicit Line Joining.

Code that is between parentheses is implicitly part of the same instruction, therefore, you can 'shorten' your expression by spreading it in multiple lines:

tree_top = os.path.abspath(
    os.path.expanduser(
        os.path.expandvars(
            sys.argv[1]
        )
    )
)

Now, each line comes under 80 characters and is clean PEP8 code.

If each step of your operation was more clearly defined, using intermediary variables would also be a good way to shorten each individual lines. In some cases, it can help make the code clearer, but here the intermediary steps are less useful

Upvotes: 4

jonrsharpe
jonrsharpe

Reputation: 121966

The easiest way to reduce the width is to use implicit line continuation within parentheses:

tree_top = os.path.abspath(
    os.path.expanduser(
        os.path.expandvars(sys.argv[1])
    )
)

Alternatively, just select the parts of os.path that you need:

from os.path import abspath, expanduser, expandvars

tree_top = abspath(expanduser(expandvars(sys.argv[1])))

or use some combination of the two.

Upvotes: 11

Related Questions