I always leave a blank line after class definition and the code seems to be PEP8 compliant, as no warning is raised for this. I do this because I found it more readable than writing all together.

class Area(BaseModel):

    name = models.CharField(_("Name"), max_length=30)
    slug = models.SlugField(_("Slug"), max_length=30, unique=True)

    class Meta(BaseModel.Meta):

        verbose_name = _("Area")
        verbose_name_plural = _("Areas")
        ordering = [
            "name",
        ]

However, when I read PEP8 code compliant. This extra space is never there and this code would look like this:

class Area(BaseModel):
    name = models.CharField(_("Name"), max_length=30)
    slug = models.SlugField(_("Slug"), max_length=30, unique=True)

    class Meta(BaseModel.Meta):
        verbose_name = _("Area")
        verbose_name_plural = _("Areas")
        ordering = [
            "name",
        ]

My question is: Is that a "bad practice" what I'm doing. Should I avoid this extra blank lines in Python?

有帮助吗?

解决方案

This is really a matter of taste. I personally include the blank line to be consisted with classes which have a docstring. Quoting PEP-0257:

Insert a blank line before and after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line; for symmetry, put a blank line between the class header and the docstring.

To illustrate:

class WithoutDocString(object):

    def __init__(self):
        pass


class WithADocString(object):

    """Summary line.

    Bla bla bla bla.
    """

    def __init__(self):
        pass

其他提示

As I understand the blank line section of PEP-8, there is some liberty on this question. Blank lines may appear in some places (separating groups of related functions) and may be omitted in other places (to group a list of one-liners).

There is no liberty, however, about blank lines after definition headers. They should not appear, conforming to the PEP-8 rules.

Your PEP-8 compliance checker does not seem to check this, though.

Generally (not PEP-8 related), I have the feeling that blank lines, as many other formatting issues, is a matter of what you are used to. There are no scientific researches I know of that show which formatting works best on unbiased developers. And most of us are biased anyway, so even this probably would not mean very much.

When editing existing code, my main approach always is to stick to the existing formatting. But that's beside the point here ;-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top