
Imports style guide
Wonderful PEP8, which you are probably familiar with if you are developing in Python, does not answer all the questions that arise during the coding process. As a result, each development team takes PEP8 as a basis and develops its own standards, which it tries to adhere to. How many teams - so many options. And this is a necessary artificial framework. Like a grid for a typographer or typesetter, it helps the code look clear, consistent and consistent. In general, code formatting is not the place to show your personality.
Before asking the main question, dear colleagues, I would like to show some examples of “liberties” that everyone takes for himself (or meekly takes someone else's decision).
I personally like more than
The distance between the import block and the first function or class is 2 empty lines.
The distance between different functions or classes is also 2 empty lines. The distance between the class methods is 1 empty line. The distance between the class header and the first method is 1 empty line.
Enumeration of elements of a list / tuple / dictionary, etc., from each new line, if everything does not fit into one:
The same goes for the long logical condition:
If there is a need to break the chain of methods into several lines, the expression is framed in brackets. No backslashes (fu fu fu).
A tuple of one element is written as
Check for None:
By the way, comments are discarded by two spaces, not one.
Among other things, I love the string method .format ().
The implicit string join looks weird, but visually nicer than concatenation by addition:
The dictionary is written as
There are more than a dozen such “fad” and I’m sure that there are people who are ready to challenge them and offer their vision of the kosher code design. But if, according to the examples given, everything is more or less clear to me, then by the design of large (really large) import blocks, everything is not yet clear.
I once met in a working draft a cloak of imports in one of the modules.
I thought to myself: “What the hell? ..” and rewrote it the way I like.
Well, you understand the principle ...
For what he did during the review. As if the previous version also has the right to life, it is convenient during the freeze and it seems to be more convenient to read it. I promised to argue my option and just give a link to this post, at the same time and find out what the Habrovsk people think about this.
So. The very idea of “every object on a new line” is important. Firstly, it’s beautiful :) Secondly, during the freeze it gives its advantages, there is no confusion. This is a useful property, we need to save it.
In the second version, the module (or package) from which we import is like the heading of a subsequent paragraph of text (imported objects). There is no need to repeat the title each time, we have already seen once from where we import and we have a line-by-line listing of what we import. If someone needs to supplement the list of imports from this source, he simply goes to the end of the list, presses Enter and adds his own (+ comma, with a thought about the neighbor). It looks cleaner, the lines are shorter, they are read faster, you do not need to append / copy the source every time, which, by the way, can be renamed. No need to ignore the gaze part
In general, there are a lot of options for block design with imports. About a dozen, no less. How exactly to break the lines, according to what criteria, whether to sort alphabetically, to transfer or not the opening / closing bracket ... But you need to come to some common denominator, the whole development team must adhere to the accepted agreement. Otherwise anarchy. I know people who don’t bother with this at all, since PyCharm has a wonderful auto import and there is a point of view that it doesn’t matter what happens in this block. But we have a large team, PyCharm is using only me along the way (most are on Sublime, the rest are Vim, Emacs, Eclipse), we need to make sure that everyone is comfortable and understandable. Well, from my point of view, imports are also a code that deserves to look good. Maintainability, after all. What do you think?
So the survey.
Before asking the main question, dear colleagues, I would like to show some examples of “liberties” that everyone takes for himself (or meekly takes someone else's decision).
"""
Very long multiline description
about function or class method
"""
I personally like more than
"""Very long multiline description
about function or class method
"""
The distance between the import block and the first function or class is 2 empty lines.
from unittest import TestCase
class BaseURLGeneratorTestCase(TestCase):
pass
The distance between different functions or classes is also 2 empty lines. The distance between the class methods is 1 empty line. The distance between the class header and the first method is 1 empty line.
class TestSomething(TestCase):
def test_some_stuff(self):
pass
def test_another_stuff(self):
pass
Enumeration of elements of a list / tuple / dictionary, etc., from each new line, if everything does not fit into one:
records = [first_object, second_object]
records = [
first_object,
second_object,
third_object,
fourth_object,
]
The same goes for the long logical condition:
if (
user.is_client()
and user.has_manager()
and not user.is_banned()
and user.has_company()
):
do_something()
If there is a need to break the chain of methods into several lines, the expression is framed in brackets. No backslashes (fu fu fu).
templates = (
EmailTemplate.query
.filter(EmailTemplate.type_id == type.id)
.order_by(EmailTemplate.title)
.all()
)
A tuple of one element is written as
x = (y,)
or x = y,
, but it looks awful, so I prefer in this case to get by with a list x = [y]
or a lot x = {y}
, there are other options. Check for None:
x = None
if x:
do_something() # фигня
if x is not None:
do_something() # так-то лучше
By the way, comments are discarded by two spaces, not one.
Among other things, I love the string method .format ().
'{0}'.format(x)
I like more than '%s' % x
. But when there are more than two insertion points, you should use named arguments:'{name} {surname}, {address}'.format(
name=name,
surname=surname,
address=address,
)
The implicit string join looks weird, but visually nicer than concatenation by addition:
message = _(
u"Зачем соединять строки через +, "
u"если есть вот такая вот фича?"
)
The dictionary is written as
{'key': value, 'another_key': another_value}
, not how dict(key=value, another_key=another_value)
. It is visually cleaner, it is highlighted by all normal editors as a dictionary, and not as passing named arguments, moreover, creating such an object works faster than through dict (). There are more than a dozen such “fad” and I’m sure that there are people who are ready to challenge them and offer their vision of the kosher code design. But if, according to the examples given, everything is more or less clear to me, then by the design of large (really large) import blocks, everything is not yet clear.
I once met in a working draft a cloak of imports in one of the modules.
...
from lib.util import https_wrapper, logout_user
from lib.util import ajax, sudo_su, sudo_exit, transactional
from lib.util import has_auth, get_demo
from lib.util import get_user_registration_source_id
from lib.util import ajax_validate, generate_timed_hash, get_auth_user
from lib.util import render_template, check_timed_hash
from lib.util import create_validate_response, update_user_in_session
from lib.util import prepare_watermark_text
...
I thought to myself: “What the hell? ..” and rewrote it the way I like.
from lib.util import (
https_wrapper,
logout_user,
ajax,
sudo_su,
sudo_exit,
transactional,
has_auth,
get_demo,
)
Well, you understand the principle ...
For what he did during the review. As if the previous version also has the right to life, it is convenient during the freeze and it seems to be more convenient to read it. I promised to argue my option and just give a link to this post, at the same time and find out what the Habrovsk people think about this.
So. The very idea of “every object on a new line” is important. Firstly, it’s beautiful :) Secondly, during the freeze it gives its advantages, there is no confusion. This is a useful property, we need to save it.
In the second version, the module (or package) from which we import is like the heading of a subsequent paragraph of text (imported objects). There is no need to repeat the title each time, we have already seen once from where we import and we have a line-by-line listing of what we import. If someone needs to supplement the list of imports from this source, he simply goes to the end of the list, presses Enter and adds his own (+ comma, with a thought about the neighbor). It looks cleaner, the lines are shorter, they are read faster, you do not need to append / copy the source every time, which, by the way, can be renamed. No need to ignore the gaze part
from bla_bla_bla import
for each line. Sliding 4 spaces through the eyes is much easier.In general, there are a lot of options for block design with imports. About a dozen, no less. How exactly to break the lines, according to what criteria, whether to sort alphabetically, to transfer or not the opening / closing bracket ... But you need to come to some common denominator, the whole development team must adhere to the accepted agreement. Otherwise anarchy. I know people who don’t bother with this at all, since PyCharm has a wonderful auto import and there is a point of view that it doesn’t matter what happens in this block. But we have a large team, PyCharm is using only me along the way (most are on Sublime, the rest are Vim, Emacs, Eclipse), we need to make sure that everyone is comfortable and understandable. Well, from my point of view, imports are also a code that deserves to look good. Maintainability, after all. What do you think?
So the survey.
Only registered users can participate in the survey. Please come in.
How to make out a block with imports?
- 23.3% List the import source in each row 32
- 29.9% Indicate the source of import once, and with each new line a list of imported objects 41
- 12.4% Indicate the source of import once, but list everything in one line 17
- 18.9% Import only the module itself, not objects from it 26
- 14.5% Do not bother like this, these are just imports 20
- 0.7% I will indicate my option in the comments 1