Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long imports in Python

I sometimes 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?

like image 465
Vorac Avatar asked Jun 24 '13 10:06

Vorac


People also ask

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.

How do I fix an import problem in Python?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What are the imports in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


1 Answers

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

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).

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.

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 ) 
like image 176
Wolph Avatar answered Oct 04 '22 09:10

Wolph