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
Rust like Option and Result types in Python

Option Rust-like Option and Result types in Python, slotted and fully typed. An Option type represents an optional value, every Option is either Some

45 Dec 13, 2022
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 03, 2022
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 08, 2023
Pymxs, the 3DsMax bindings of Maxscript to Python doesn't come with any stubs

PyMXS Stubs generator What Pymxs, the 3DsMax bindings of Maxscript to Python doe

Frieder Erdmann 19 Dec 27, 2022
Pylint plugin to enforce some secure coding standards for Python.

Pylint Secure Coding Standard Plugin pylint plugin that enforces some secure coding standards. Installation pip install pylint-secure-coding-standard

Nguyen Damien 2 Jan 04, 2022
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
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
A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

flake8-bugbear A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycode

Python Code Quality Authority 869 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
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
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
Tools for improving Python imports

imptools Tools for improving Python imports. Installation pip3 install imptools Overview Detailed docs import_path Import a module from any path on th

Danijar Hafner 7 Aug 07, 2022
A static-analysis bot for Github

Imhotep, the peaceful builder. What is it? Imhotep is a tool which will comment on commits coming into your repository and check for syntactic errors

Justin Abrahms 221 Nov 10, 2022
The mypy playground. Try mypy with your web browser.

mypy-playground The mypy playground provides Web UI to run mypy in the sandbox: Features Web UI and sandbox for running mypy eas

Yusuke Miyazaki 57 Jan 02, 2023
Design by contract for Python. Write bug-free code. Add a few decorators, get static analysis and tests for free.

A Python library for design by contract (DbC) and checking values, exceptions, and side-effects. In a nutshell, deal empowers you to write bug-free co

Life4 473 Dec 28, 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 08, 2023
Typed interface stubs for Pythonista iOS

Pythonista Stubs Stubs for the Pythonista iOS API. This allows for better error detection and IDE / editor autocomplete. Installation and Usage pip in

Harold Martin 12 Jul 14, 2020
Tool to automatically fix some issues reported by flake8 (forked from autoflake).

autoflake8 Introduction autoflake8 removes unused imports and unused variables from Python code. It makes use of pyflakes to do this. autoflake8 also

francisco souza 27 Sep 08, 2022
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