Long imports in Python

2019-01-26 03:53发布

I seldom have to write something like

from blqblq.lqlqlqlq.bla import fobarbazbarbarbazar as foo
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

which takes more than 80 characters. This situation is not covered in the official Python coding style guide. How do I write such imports pythonically?

2条回答
SAY GOODBYE
2楼-- · 2019-01-26 04:14

http://www.python.org/dev/peps/pep-0008/#maximum-line-length

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

So in your case this could be:

from blqblq.lqlqlqlq.bla import (
                                 fobarbazbarbarbazar
                                 as foo)
from matplotlib.backends.backend_qt4agg import (
                                                 FigureCanvasQTAgg
                                                 as FigureCanvas)

Personally I always use this style which I find more readable with long lines:

# Just 1 indent
from blqblq.lqlqlqlq.bla import (
    fobarbazbarbarbazar
    as foo
) # end at the next line so it's always clear where what ends

from matplotlib.backends.backend_qt4agg import (
    FigureCanvasQTAgg as FigureCanvas
)
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-26 04:25

This is the PEP8 documentation for long imports:

Currently, if you want to import a lot of names from a module or package, you have to choose one of several unpalatable options:

Write a long line with backslash continuations:

from Tkinter import Tk, Frame, Button, Entry, Canvas, Text, \
     LEFT, DISABLED, NORMAL, RIDGE, END 

Write multiple import statements:

from Tkinter import Tk, Frame, Button, Entry, Canvas, Text 
from Tkinter import LEFT, DISABLED, NORMAL, RIDGE, END 

( import * is not an option ;-)

Instead, it should be possible to use Python's standard grouping mechanism (parentheses) to write the import statement:

from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,
    LEFT, DISABLED, NORMAL, RIDGE, END) 

This part of the proposal had BDFL approval from the beginning.

Parentheses support was added to Python 2.4.

查看更多
登录 后发表回答