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
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.2k Jan 3, 2023
docstring style checker

pydocstyle - docstring style checker pydocstyle is a static analysis tool for checking compliance with Python docstring conventions. pydocstyle suppor

Python Code Quality Authority 982 Jan 3, 2023
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 8, 2023
A Python Parser

parso - A Python Parser Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python

Dave Halter 520 Dec 26, 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
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 4, 2023
A static type analyzer for Python code

pytype - ?? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 4k Dec 31, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 1, 2023
Tool to check the completeness of MANIFEST.in for Python packages

check-manifest Are you a Python developer? Have you uploaded packages to the Python Package Index? Have you accidentally uploaded broken packages with

Marius Gedminas 270 Dec 26, 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
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022
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
Check for python builtins being used as variables or parameters

Flake8 Builtins plugin Check for python builtins being used as variables or parameters. Imagine some code like this: def max_values(list, list2):

Gil Forcada Codinachs 98 Jan 8, 2023
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
Custom Python linting through AST expressions

bellybutton bellybutton is a customizable, easy-to-configure linting engine for Python. What is this good for? Tools like pylint and flake8 provide, o

H. Chase Stevens 249 Dec 31, 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 1, 2023
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 967 Jan 7, 2023
Flake8 extension for enforcing trailing commas in python

Flake8 Extension to enforce better comma placement. Usage If you are using flake8 it's as easy as: pip install flake8-commas Now you can avoid those a

Python Code Quality Authority 127 Sep 3, 2022
Tool for pinpointing circular imports in Python. Find cyclic imports in any project

Pycycle: Find and fix circular imports in python projects Pycycle is an experimental project that aims to help python developers fix their circular de

Vadim Kravcenko 311 Dec 15, 2022