Naming Convention checker for Python

Overview

PEP 8 Naming Conventions

Check your code against PEP 8 naming conventions.

This module provides a plugin for flake8, the Python code checker.

(It replaces the plugin flint-naming for the flint checker.)

Installation

You can install, upgrade, uninstall pep8-naming with these commands:

$ pip install pep8-naming
$ pip install --upgrade pep8-naming
$ pip uninstall pep8-naming

Plugin for Flake8

When both flake8 and pep8-naming are installed, the plugin is available in flake8:

$ flake8 --version
2.0 (pep8: 1.4.3, pyflakes: 0.6.1, naming: 0.2)

By default the plugin is enabled.

Error Codes

These error codes are emitted:

code sample message
N801 class names should use CapWords convention
N802 function name should be lowercase
N803 argument name should be lowercase
N804 first argument of a classmethod should be named 'cls'
N805 first argument of a method should be named 'self'
N806 variable in function should be lowercase
N807 function name should not start and end with '__'
   
N811 constant imported as non constant
N812 lowercase imported as non lowercase
N813 camelcase imported as lowercase
N814 camelcase imported as constant
N815 mixedCase variable in class scope
N816 mixedCase variable in global scope
N817 camelcase imported as acronym

Options

The following flake8 options are added:

--ignore-names

Ignore errors for specific names or glob patterns.

Currently, this option can only be used for N802, N803, N804, N805, N806, N815, and N816 errors.

Default: setUp,tearDown,setUpClass,tearDownClass,setUpTestData,failureException,longMessage,maxDiff.

--classmethod-decorators
 

List of method decorators pep8-naming plugin should consider class method.

Used to prevent false N804 errors.

Default: classmethod.

--staticmethod-decorators
 

List of method decorators pep8-naming plugin should consider static method.

Used to prevent false N805 errors.

Default: staticmethod.

Comments
  • Consider all metaclass methods to be class methods

    Consider all metaclass methods to be class methods

    It's a widely used (but perhaps not official?) convention to consider a metaclass's methods to be class methods and to use cls as the first argument (rather than self).

    Use the simple heuristic of "class inherits from type" to identify metaclasses and mark all of their methods as CLASSMETHOD.

    opened by jparise 15
  • fix: update flake8 output

    fix: update flake8 output

    The pep8 entry was quite confusing to me and I don't think it will ever show up with a newish flake8 version. Also update naming to the latest release.

    opened by fliiiix 11
  • Allow camelCase for python standard libraries.

    Allow camelCase for python standard libraries.

    (Unfortunately) some libraries in the python standard library do not follow pep8. This means that people using them are forced to write non pep8-compliant code. This code should be accepted by the pep8-naming plugin. For example unittest.TestCase is meant to be overridden so setUp and tearDown can be implemented. The same goes for logging.Logger.

    enhancement needs patch 
    opened by remcohaszing 10
  • Version 0.11.0 breaks with AttributeError

    Version 0.11.0 breaks with AttributeError

    When I run flake8 with the new pep8-naming version 0.11.0, I get an AttributeError from pep8ext_naming.py

    $ .venv/bin/flake8
    multiprocessing.pool.RemoteTraceback: 
    """
    Traceback (most recent call last):
      File "/path/python/envs/3.7.6/lib/python3.7/multiprocessing/pool.py", line 121, in worker
        result = (True, func(*args, **kwds))
      File "/path/python/envs/3.7.6/lib/python3.7/multiprocessing/pool.py", line 44, in mapstar
        return list(map(*args))
      File "/path/.venv/lib/python3.7/site-packages/flake8/checker.py", line 655, in _run_checks
        return checker.run_checks()
      File "/path/.venv/lib/python3.7/site-packages/flake8/checker.py", line 589, in run_checks
        self.run_ast_checks()
      File "/path/.venv/lib/python3.7/site-packages/flake8/checker.py", line 496, in run_ast_checks
        for (line_number, offset, text, _) in runner:
      File "/path/.venv/lib/python3.7/site-packages/pep8ext_naming.py", line 195, in visit_tree
        for error in self.visit_tree(child):
      File "/path/.venv/lib/python3.7/site-packages/pep8ext_naming.py", line 191, in visit_tree
        for error in self.visit_node(node):
      File "/path/.venv/lib/python3.7/site-packages/pep8ext_naming.py", line 201, in visit_node
        self.tag_class_functions(node)
      File "/path/.venv/lib/python3.7/site-packages/pep8ext_naming.py", line 242, in tag_class_functions
        iter_child_nodes(cls_node), ismetaclass, late_decoration)
      File "/path/.venv/lib/python3.7/site-packages/pep8ext_naming.py", line 259, in set_function_nodes_types
        name = d.func.id if isinstance(d, ast.Call) else d.id
    AttributeError: 'Attribute' object has no attribute 'id'
    """
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File ".venv/bin/flake8", line 8, in <module>
        sys.exit(main())
      File "path/.venv/lib/python3.7/site-packages/flake8/main/cli.py", line 22, in main
        app.run(argv)
      File "/path/.venv/lib/python3.7/site-packages/flake8/main/application.py", line 360, in run
        self._run(argv)
      File "/path/.venv/lib/python3.7/site-packages/flake8/main/application.py", line 348, in _run
        self.run_checks()
      File "/path/.venv/lib/python3.7/site-packages/flake8/main/application.py", line 262, in run_checks
        self.file_checker_manager.run()
      File "/path/.venv/lib/python3.7/site-packages/flake8/checker.py", line 323, in run
        self.run_parallel()
      File "/path/.venv/lib/python3.7/site-packages/flake8/checker.py", line 289, in run_parallel
        for ret in pool_map:
      File "/path/python/envs/3.7.6/lib/python3.7/multiprocessing/pool.py", line 354, in <genexpr>
        return (item for chunk in result for item in chunk)
      File "/path/python/envs/3.7.6/lib/python3.7/multiprocessing/pool.py", line 748, in next
        raise value
    AttributeError: 'Attribute' object has no attribute 'id'
    

    My guess is that it is not only Python 3.7, but that is all I've tried.

    bug 
    opened by SethMMorton 9
  • N812 for uppercase shorthand

    N812 for uppercase shorthand

    I believe it's common practice to shorten long imports from selenium like it is done in Selenium docs: http://selenium-python.readthedocs.io/waits.html

    But pep8-naming detects error:

    from selenium.webdriver.support import expected_conditions as EC
    ^
    1     N812 lowercase 'EC' imported as non lowercase
    1
    

    I think the intention of N812 was to avoid importing lowercase as CamelCase, but this one is actually UPPERCASE, so I think it's false positive.

    opened by peterdemin 9
  • Class attributes naming rules

    Class attributes naming rules

    I have occasionally found out that it is possible to use any case for naming class attributes:

    class Test(object):
        camelCase = 1
        snake_case = 2
        UPPER_CASE = 3
    
    

    flake8 and pep8-naming won't complain about it.

    Since https://www.python.org/dev/peps/pep-0008 does not say a word about class attributes naming style, I believe that it might be a hot discussion.

    In my opinion class attributes should be using snake_case by default. What do you think? Thanks!

    opened by sobolevn 7
  • Update `pep8-naming` compatibility with flake8

    Update `pep8-naming` compatibility with flake8

    pep8-naming tests fail for flake8 v3/v4; avoid suggesting that it works

    Additionally, v6 added one more required kwarg. Let's add that one too.

    Signed-off-by: Stavros Ntentos [email protected]

    opened by stdedos 6
  • Broken test with flake8>=3.9.1

    Broken test with flake8>=3.9.1

    After upgrading to flake>=3.9.1 the following test failure came up.

    Traceback (most recent call last):
      File "run_tests.py", line 117, in <module>
        main()
      File "run_tests.py", line 34, in main
        errors += test_file(filename, testcase, code, options)
      File "run_tests.py", line 99, in test_file
        parse_options(checker, options)
      File "run_tests.py", line 90, in parse_options
        checker.parse_options(processed_options)
      File "/nix/store/9fggrr07qvlrqqqf2lpy9ynfn30v1ans-python3.8-pep8-naming-0.11.1/lib/python3.8/site-packages/pep8ext_naming.py", line 181, in parse_options
        engine = style_guide.DecisionEngine(options)
      File "/nix/store/mr2dci4kaf4illh63hb264lhn4vp6s1w-python3.8-flake8-3.9.1/lib/python3.8/site-packages/flake8/style_guide.py", line 171, in __init__
        ).union(options.extended_default_ignore)
    AttributeError: 'Values' object has no attribute 'extended_default_ignore'
    

    Seems related to this change: https://github.com/PyCQA/flake8/pull/1317

    opened by mweinelt 6
  • 'Attribute' object has no attribute 'id'

    'Attribute' object has no attribute 'id'

    Here's an interesting one (see last line of traceback):

    Traceback (most recent call last):
      File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 119, in worker
        result = (True, func(*args, **kwds))
      File "/usr/local/lib/python3.6/site-packages/flake8/checker.py", line 648, in _run_checks
        return checker.run_checks()
      File "/usr/local/lib/python3.6/site-packages/flake8/checker.py", line 579, in run_checks
        self.run_ast_checks()
      File "/usr/local/lib/python3.6/site-packages/flake8/checker.py", line 493, in run_ast_checks
        for (line_number, offset, text, check) in runner:
      File "/usr/local/lib/python3.6/site-packages/pep8ext_naming.py", line 146, in visit_tree
        for error in self.visit_tree(child):
      File "/usr/local/lib/python3.6/site-packages/pep8ext_naming.py", line 142, in visit_tree
        for error in self.visit_node(node):
      File "/usr/local/lib/python3.6/site-packages/pep8ext_naming.py", line 152, in visit_node
        self.tag_class_functions(node)
      File "/usr/local/lib/python3.6/site-packages/pep8ext_naming.py", line 185, in tag_class_functions
        ismetaclass = any(name for name in cls_node.bases if name.id == 'type')
      File "/usr/local/lib/python3.6/site-packages/pep8ext_naming.py", line 185, in <genexpr>
        ismetaclass = any(name for name in cls_node.bases if name.id == 'type')
    AttributeError: 'Attribute' object has no attribute 'id'
    

    It is interesting because before I started whittling down the flake8 errors (all I was doing was adding documentation really), pep8-naming was doing OK. Then out of the blue this crash!

    I found a similar issue which was resolved by checking if id was available.

    Before I start working on a PR that changes any xxx.id to be getattr(xxx, "id", None), since there are a lot more uses of .id in pep8-naming, anything special to look out for?

    The file being checked here is actually deliberately breaking pep8-naming conventions, but I was working on the other flake8 errors before I #noqa the classes that intentionally break things. I wonder if that is somehow related (the fact that there are actual errors causing this issue)?

    opened by svenevs 6
  • Multiple underscores cause N807 false-positive

    Multiple underscores cause N807 false-positive

    This may be related to #45:

    def foo_():
        pass
    
    
    def foo__():
        pass
    
    
    def test___main__():
        """Test python -m functionality."""
        with pytest.raises(SystemExit) as excinfo:
            with unittest.mock.patch('sys.argv', []):
                # pylint: disable=unused-variable, redefined-outer-name
                import backlog.__main__  # noqa: F401
        assert excinfo.value.code == 0
    
    /home/david/Projects/backlog/tests/test_cli.py:14:5: N802 function name 'foo__' should be lowercase xxx
    /home/david/Projects/backlog/tests/test_cli.py:18:5: N802 function name 'test___main__' should be lowercase xxx
    
    needs patch 
    opened by dmtucker 6
  • Add configurable list of classmethod / staticmethod decorators

    Add configurable list of classmethod / staticmethod decorators

    • Add classmethod-decorator and staticmethod-decorator config parameters
    • Add support for parsing CLI-style flake8-config parameters in testing framework.
    • Remove support for multiple codes in a testcase, since it was never used.
    • Add tests for late-decorated methods

    Fixes #38

    opened by saifelse 6
  • Add N810 specifically for package or module imports

    Add N810 specifically for package or module imports

    These are differences in behavior based on existing and new test cases:

    statement | before | now -- | -- | -- import os as OS | N812 lowercase 'os' imported as non lowercase 'OS' | N810 package or module 'os' imported as non lowercase 'OS' import GOOD as good | N811 constant 'GOOD' imported as non constant 'good' | Okay (because GOOD is a package or module) import good as BAD | N812 lowercase 'good' imported as non lowercase 'BAD' | N810 package or module 'good' imported as non lowercase 'BAD' import good as Bad | N812 lowercase 'good' imported as non lowercase 'Bad' | N810 package or module 'good' imported as non lowercase 'Bad' import GOOD as Γ | Okay | N810 package or module 'GOOD' imported as non lowercase 'Γ'

    Hope it makes sense based on the discussion in #201.

    opened by ericbn 1
  • "camelcase imported as lowercase" fails even when only parent package is camelcase

    For example, this code:

    import SalesforcePy.commons as sfc
    

    fails with:

    ./test.py:1:2: N813 camelcase 'SalesforcePy.commons' imported as lowercase 'sfc'
    

    Shouldn't pep-naming just look at the package name being imported (commons) instead of looking at the parent package names too, and then not fail in this case?

    I'm assuming this rule exists for when a class name is being imported, as discussed in https://stackoverflow.com/a/37590149/2654518. In this case:

    from SalesforcePy.commons import BaseRequest as baserequest
    

    sure should fail with:

    ./test.py:1:2: N813 camelcase 'BaseRequest' imported as lowercase 'baserequest'
    
    opened by ericbn 11
  • False positive for HTTP request handler do_METHOD methods

    False positive for HTTP request handler do_METHOD methods

    The built-in base HTTP request handler class in http.server asks you to create methods named (for example) do_GET, do_POST, etc. Rule N802 warns about these methods.

    opened by djmattyg007 1
  • False positive for N805 in a child class

    False positive for N805 in a child class

    $ cat -n a.py
         1  # pylint: disable=missing-class-docstring, missing-module-docstring
         2  
         3  class Foo(type):
         4      pass
         5  
         6  
         7  class Bar(Foo):
         8      def __init__(cls):
         9          super().__init__()
    $ flake8 --ignore=D100,D101,D107 a.py 
    a.py:8:19: N805 first argument of a method should be named 'self'
    

    PEP8: Always use cls for the first argument to class methods.

    Note that pylint is correct here:

    $ pylint a.py
    
    --------------------------------------------------------------------
    Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
    
    opened by skirpichev 3
  • N815: Ignore TypedDict class variable casing

    N815: Ignore TypedDict class variable casing

    Prosed fix for #178

    Add specific exemption from N815 for all subclasses of TypedDict because class variable naming conventions should not apply to dictionary keys.

    I've tried to reuse code from the rule for Exceptions (N818) as per the suggestion on #178.

    This is my first time working with the ast module or with any flake8 plugin so please bear that in mind when reviewing this PR. Any advice on whether it's reasonable to tag every ClassDef with the names of its superclasses, and potential performance concerns around that, would be very welcome. On balance, I thought it may be preferable to do this rather than determining the superclasses again for every variable in a class.

    Thanks :)

    opened by danielpatrickdotdev 3
Releases(0.13.3)
Owner
Python Code Quality Authority
Organization for code quality tools (and plugins) for the Python programming language
Python Code Quality Authority
❄️ A flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 2022
A python documentation linter which checks that the docstring description matches the definition.

Darglint A functional docstring linter which checks whether a docstring's description matches the actual function/method implementation. Darglint expe

Terrence Reilly 463 Dec 31, 2022
A framework for detecting, highlighting and correcting grammatical errors on natural language text.

Gramformer Human and machine generated text often suffer from grammatical and/or typographical errors. It can be spelling, punctuation, grammatical or

Prithivida 1.3k Jan 08, 2023
MonkeyType as a pytest plugin.

MonkeyType as a pytest plugin.

Marius van Niekerk 36 Nov 24, 2022
Static Typing for Python

Python static typing home. Contains the source for typing_extensions and the documentation. Also hosts a user help forum.

Python 1.3k Jan 06, 2023
Flashcards - A flash card application with 2 optional command line arguments

Flashcards A flash card application with 2 optional command line arguments impor

Özgür Yildirim 2 Jul 15, 2022
Naming Convention checker for Python

PEP 8 Naming Conventions Check your code against PEP 8 naming conventions. This module provides a plugin for flake8, the Python code checker. (It repl

Python Code Quality Authority 411 Dec 23, 2022
Mylint - My really simple rendition of how a linter works.

mylint My really simple rendition of how a linter works. This original version was written for my AST article. Since then I've added tests and turned

Tushar Sadhwani 2 Dec 29, 2021
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 194 Dec 19, 2022
Plugin for mypy to support zope.interface

Plugin for mypy to support zope.interface The goal is to be able to make zope interfaces to be treated as types in mypy sense. Usage Install both mypy

Shoobx 36 Oct 29, 2022
MyPy types for WSGI applications

WSGI Types for Python This is an attempt to bring some type safety to WSGI applications using Python's new typing features (TypedDicts, Protocols). It

Blake Williams 2 Aug 18, 2021
A plugin for flake8 integrating Mypy.

flake8-mypy NOTE: THIS PROJECT IS DEAD It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plu

Łukasz Langa 103 Jun 23, 2022
mypy plugin for loguru

loguru-mypy A fancy plugin to boost up your logging with loguru mypy compatibility logoru-mypy should be compatible with mypy=0.770. Currently there

Tomasz Trębski 13 Nov 02, 2022
A simple plugin that allows running mypy from PyCharm and navigate between errors

mypy-PyCharm-plugin The plugin provides a simple terminal to run fast mypy daemon from PyCharm with a single click or hotkey and easily navigate throu

Dropbox 301 Dec 09, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 03, 2023
PEP-484 typing stubs for SQLAlchemy 1.4 and SQLAlchemy 2.0

SQLAlchemy 2 Stubs These are PEP-484 typing stubs for SQLAlchemy 1.4 and 2.0. They are released concurrently along with a Mypy extension which is desi

SQLAlchemy 139 Dec 30, 2022
Flake8 wrapper to make it nice, legacy-friendly, configurable.

THE PROJECT IS ARCHIVED Forks: https://github.com/orsinium/forks It's a Flake8 wrapper to make it cool. Lint md, rst, ipynb, and more. Shareable and r

Life4 232 Dec 16, 2022
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 06, 2023
Flake8 extension for checking quotes in python

Flake8 Extension to lint for quotes. Major update in 2.0.0 We automatically encourage avoiding escaping quotes as per PEP 8. To disable this, use --no

Zachary Heller 157 Dec 13, 2022
Automated security testing using bandit and flake8.

flake8-bandit Automated security testing built right into your workflow! You already use flake8 to lint all your code for errors, ensure docstrings ar

Tyler Wince 96 Jan 01, 2023