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
Flake8 plugin for managing type-checking imports & forward references

flake8-type-checking Lets you know which imports to put in type-checking blocks. For the imports you've already defined inside type-checking blocks, i

snok 67 Dec 16, 2022
Utilities for refactoring imports in python-like syntax.

aspy.refactor_imports Utilities for refactoring imports in python-like syntax. Installation pip install aspy.refactor_imports Examples aspy.refactor_i

Anthony Sottile 20 Nov 01, 2022
Run isort, pyupgrade, mypy, pylint, flake8, and more on Jupyter Notebooks

Run isort, pyupgrade, mypy, pylint, flake8, mdformat, black, blacken-docs, and more on Jupyter Notebooks ✅ handles IPython magics robustly ✅ respects

663 Jan 08, 2023
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
Reference implementation of sentinels for the Python stdlib

Sentinels This is a reference implementation of a utility for the definition of sentinel values in Python. This also includes a draft PEP for the incl

Tal Einat 22 Aug 27, 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
flake8 plugin that integrates isort

Flake8 meet isort Use isort to check if the imports on your python files are sorted the way you expect. Add an .isort.cfg to define how you want your

Gil Forcada Codinachs 139 Nov 08, 2022
Convert relative imports to absolute

absolufy-imports A tool and pre-commit hook to automatically convert relative imports to absolute. Installation $ pip install absolufy-imports Usage a

Marco Gorelli 130 Dec 30, 2022
Python classes with types validation at runtime.

typedclasses Python classes with types validation at runtime. (Experimental & Under Development) Installation You can install this library using Pytho

Izhar Ahmad 8 Feb 06, 2022
Unbearably fast O(1) runtime type-checking in pure Python.

Look for the bare necessities, the simple bare necessities. Forget about your worries and your strife. — The Jungle Book.

beartype 1.4k Jan 01, 2023
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 program which checks Python source files for errors

Pyflakes A simple program which checks Python source files for errors. Pyflakes analyzes programs and detects various errors. It works by parsing the

Python Code Quality Authority 1.2k Dec 30, 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
An open-source, mini imitation of GitHub Copilot for Emacs.

Second Mate An open-source, mini imitation of GitHub Copilot using EleutherAI GPT-Neo-2.7B (via Huggingface Model Hub) for Emacs. This is a much small

Sam Rawal 238 Dec 27, 2022
Pyright extension for coc.nvim

coc-pyright Pyright extension for coc.nvim Install :CocInstall coc-pyright Note: Pyright may not work as expected if can't detect project root correct

Heyward Fann 1.1k Jan 02, 2023
Flake8 plugin to validate annotations complexity

flake8-annotations-complexity An extension for flake8 to report on too complex type annotations. Complex type annotations often means bad annotations

BestDoctor 41 Dec 28, 2022
flake8 plugin to run black for checking Python coding style

flake8-black Introduction This is an MIT licensed flake8 plugin for validating Python code style with the command line code formatting tool black. It

Peter Cock 146 Dec 15, 2022
Type annotations builder for boto3 compatible with VSCode, PyCharm, Emacs, Sublime Text, pyright and mypy.

mypy_boto3_builder Type annotations builder for boto3-stubs project. Compatible with VSCode, PyCharm, Emacs, Sublime Text, mypy, pyright and other too

Vlad Emelianov 2 Dec 05, 2022
OpenStack Hacking Style Checks. Mirror of code maintained at opendev.org.

Introduction hacking is a set of flake8 plugins that test and enforce the OpenStack StyleGuide Hacking pins its dependencies, as a new release of some

Mirrors of opendev.org/openstack 224 Jan 05, 2023
Performant type-checking for python.

Pyre is a performant type checker for Python compliant with PEP 484. Pyre can analyze codebases with millions of lines of code incrementally – providi

Facebook 6.2k Jan 04, 2023