Coder Social home page Coder Social logo

pycqa / pep8-naming Goto Github PK

View Code? Open in Web Editor NEW
491.0 16.0 179.0 211 KB

Naming Convention checker for Python

Home Page: pypi.python.org/pypi/pep8-naming

License: Other

Python 100.00%
python naming-conventions pep8 linter-plugin linter-flake8 flake8 flake8-plugin flake8-extensions

pep8-naming's Introduction

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
4.0.1 (mccabe: 0.6.1, naming: 0.13.0, pycodestyle: 2.8.0, pyflakes: 2.4.0) CPython 3.8.10 on Linux

By default the plugin is enabled.

Error Codes

These error codes are emitted:

code sample message
_N801 class names should use CapWords convention (class names)
_N802 function name should be lowercase (function names)
_N803 argument name should be lowercase (function arguments)
_N804 first argument of a classmethod should be named 'cls' (function arguments)
_N805 first argument of a method should be named 'self' (function arguments)
_N806 variable in function should be lowercase
_N807 function name should not start and end with '__'
_N811 constant imported as non constant (constants)
_N812 lowercase imported as non-lowercase
_N813 camelcase imported as lowercase
_N814 camelcase imported as constant (distinct from N817 for selective enforcement)
_N815 mixedCase variable in class scope (constants, method names)
_N816 mixedCase variable in global scope (constants)
_N817 camelcase imported as acronym (distinct from N814 for selective enforcement)
_N818 error suffix in exception names (exceptions)

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,setUpModule,tearDownModule,asyncSetUp,asyncTearDown,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.

FAQ

How do I configure classmethod_decorators to recognize SQLAlchemy class methods?

classmethod_decorators =
    classmethod
    declared_attr
    expression
    comparator

pep8-naming's People

Contributors

5j9 avatar asottile avatar carreau avatar cclauss avatar di avatar ecolell avatar edwardbetts avatar ericvw avatar f213 avatar fliiiix avatar florentx avatar frewsxcv avatar geofft avatar gforcada avatar graingert avatar hugovk avatar janlikar avatar jonblum avatar jparise avatar kdopen avatar lordmauve avatar malsyned avatar mwhudson avatar pvanderlinden avatar ramnes avatar saifelse avatar scop avatar sigmavirus24 avatar stdedos avatar stephan-hof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pep8-naming's Issues

TestCase attributes trigger N815

With the recent release of pep-8-naming I suddenly get N815 warnings for the maxDiff attribute on unittest.TestCases (https://docs.python.org/3/library/unittest.html#unittest.TestCase.maxDiff)

I haven't verified this, but I assume other TestCase attributes will also trigger this (i.e.
failureException (https://docs.python.org/3/library/unittest.html#unittest.TestCase.failureException), longMessage (https://docs.python.org/3/library/unittest.html#unittest.TestCase.longMessage))

Config to allow decorators that function like @classmethod

In SQLAlchemy, there is a declared_attr decorator that creates class methods:
http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html#sqlalchemy.ext.declarative.declared_attr

As a result, my codebase is sprinkled with:

class SomeTable(db.Model):
    @declared_attr
    def __table_args__(cls):  # noqa: N805
        ...

It would be nice if we could have a config option that lets us declare if a decorator results in a staticmethod or classmethod as opposed to the implicit default of it being an instance method. I was thinking something like using comma separated list in the setup.cfg/tox.ini file, e.g:

[flake8]
classmethod-decorators=declared_attr
staticmethod-decorators=staticdeco1,staticdeco2

N806 Constant inside function false positive


According to test, "constants" inside functions are forbidden.
But there is no evidence of such rule in PEP8, except the statement

constants are usually defined on a module level

Which is definetely don't forbid function-level constant. It could be if it was said always
I've been arguing the topic with my teammate, and never found any direct prohibition for function-level constants. Finally, he sent me a link to this test.

I'd be very glad if you proof me wrong by pointing to direct or implicit prohibition of constants usage inside of functions/methods in PEP. Or proof me right and update test (though I currently have no idea how to separate simple variable assignemnt from "constant" definition.

Just for example, one of the cases is:

class TestCase:
     URL_1 = <some_value>
     URL_2 = <some_value>
     def test_1:
          ... URL_1 usage
     def test_2:
          ... URL_2 usage

versus

class TestCase:
    def test_1:
        URL = <some_value_for_1st_test>
        ... URL usage (may be multiple times)
    def test_2:
        URL = <some_value_for_2nd_test>
        ... URL usage (may be multiple times)

I'm pretty sure that the given case is PEP-compliant and semantycally correct - it's absolutely essential to treat some values as constant inside test case and emphasize it's immutability. For example if I define dataset to make checks against it.

Python 3.4 breaks Function Argument Name checking

Looks like something in the AST modules change in python 3.4

  • In python 3.3, node.args.kwargs returns <class 'str'>
  • In python 3.4, node.args.kwargs returns <class '_ast.arg'>

This breaks FunctionArgNamesCheck.visit_functiondef() at line 187 when the return value is passed to LOWERCASE_REGEX.match() which expects a string value.

A simple test file with the following contents:

def _foo(*popenargs, **kwargs):
    pass

Will produce the following exception trace when run with python 3.4

Traceback (most recent call last):
  File "/home/keith/.virtualenvs/play34/bin/flake8", line 9, in <module>
    load_entry_point('flake8==2.1.0', 'console_scripts', 'flake8')()
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/flake8/main.py", line 32, in main
    report = flake8_style.check_files()
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8.py", line 1624, in check_files
    runner(path)
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/flake8/engine.py", line 73, in input_file
    return fchecker.check_all(expected=expected, line_offset=line_offset)
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8.py", line 1366, in check_all
    self.check_ast()
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8.py", line 1346, in check_ast
    for lineno, offset, text, check in checker.run():
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8ext_naming.py", line 78, in visit_tree
    for error in self.visit_tree(child):
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8ext_naming.py", line 74, in visit_tree
    for error in self.visit_node(node):
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8ext_naming.py", line 92, in visit_node
    for error in getattr(visitor, method)(node, self.parents):
  File "/home/keith/.virtualenvs/play34/lib/python3.4/site-packages/pep8ext_naming.py", line 188, in visit_functiondef
    if not self.check(node.args.kwarg):
TypeError: expected string or buffer

System info:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.4 LTS
Release:    12.04
Codename:   precise
$ python --version
Python 3.4.0
$ pip freeze
flake8==2.1.0
ipython==1.2.1
mccabe==0.2.1
pep8==1.4.6
pep8-naming==0.2.1
pyflakes==0.8

Originally seen on OSX 10.9.1

Allow some single uppercase letter function arguments and-or local variables

The use of single uppercase letter variables is pretty widespread in some applications, namely those that are more math-oriented. For example, X is a common variable name given to a matrix, G for graphs, etc.

My understanding of PEP8 is that these are specifically allowed (see Names to avoid), but also not specifically disallowed in the more relevant Function and method arguments section, which lists only N804 and N805.

Allow namespaces to be uppercase

In one of our projects, we use classes to emulate namespaces for constants, e.g.:

class CONTENT_TYPES:
    TEXT = 1
    IMAGE = 2
    MEDIA = 3

Would you be open to relax N801 allowing class names to be in all uppercase (or at least if the class doesn't have any methods)?

N806 - false positive for class

Regarding N806 (variable in function should be lowercase)
In Django I have a class that I create alias for which should be uppercase because it's still a class:

if a=1:
    AliasMyClass = MyClass1
if a=2:
    AliasMyClass = MyClass2

AliasMyClass.objects.create......

So it's clearly a false positive to me. Can you fix it?

New version release

Hi, thanks for this project! I am using it with great success as a dependency inside my own linter: https://github.com/wemake-services/wemake-python-styleguide

But, there were some blocking issues for me that were already addressed and merged into master.
Like #80 and #84. But these fixed are not yet released.

The latest release was made almost half a year ago. So, it would be awesome to have a new one. Currently I am blocked by it in my own releasing cycle with wemake-python-styleguide.

If there's anything I could help with - I would be more than happy to help.

package naming

I started to package this package for Macports but I find the naming confusing. This is a flake8 plugin, right?

So would a name starting like flake8-naming or flake8-pep8-naming be more appropriate. Of cause I could use different naming for MacPorts, but this probably only adds to the confusion ...

Any thoughts?

Rename/Rebrand

@gvanrossum requested that pep8 and pep257 rename themselves to avoid confusion. This flake8 plugin is far less popular, but I suspect we should rename ourselves too.

Thoughts? /cc @Nurdok @IanLee1521

Not detecting `import ... as ...` cases

Here's an example of a python code that should raise a violation (in my opinion), but does not:

import os as OS

Version information:

Β» flake8 --version
3.6.0 (naming: 0.7.0) CPython 3.6.6 on Darwin

print the actual wrong name

For example N802: function name should be lowercase would better be N802: function name "Foo" should be lowercase.
Flake8 does this for all F* error codes and it helps in finding the names faster :)

Decorator pattern should not require 'self' as first parameter

pep8-naming complains about the parameter of a decorator function. Take the example from this page: http://python-3-patterns-idioms-test.readthedocs.org/en/latest/PythonDecorators.html#using-functions-as-decorators

# PythonDecorators/entry_exit_function.py
def entry_exit(f):
    def new_f():
        print("Entering", f.__name__)
        f()
        print("Exited", f.__name__)
    return new_f

@entry_exit
def func1():
    print("inside func1()")

@entry_exit
def func2():
    print("inside func2()")

func1()
func2()
print(func1.__name__)

It (seems to be) idiomatic to call the parameter f or func or something of that nature instead of self

plugin for pytest

It would be great to have a pytest plugin in order to run it as part of the unittests

py.test --pep8-naming

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.

Functions starting/ending with a dunder

pep8-naming does not allow functions starting or ending with a dunder (__). This is not something that is disallowed by PEP8 and I think this rule should be removed. However if this check remains then it should be moved to it's own check and should not be part of the more general "functions should be lowercase" check so that people can disable it in their own projects without disabling the useful lowercase function check.

Conditional magic methods cause false positives

$ cat foo.py
class Foo:
    if x:
        def __init__():
            pass

$ flake8 foo.py --select=N
foo.py:3:13: N802 function name should be lowercase

$ flake8 --version
3.5.0 (mccabe: 0.6.1, naming: 0.4.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 3.5.3 on Linux

flake8 3.0.0b1 broke config option registration

flake8 version 3.0.0b1 was released 2016-06-25, breaking extensions.

Using pep8-naming 0.3.3 the following reported:

py34 runtests: commands[1] | flake8 /home/havok/Hacking/plantweb
Traceback (most recent call last):
  File "../bin/flake8", line 11, in <module>
    sys.exit(main())
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/main/cli.py", line 16, in main
    app.run(argv)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/main/application.py", line 292, in run
    self._run(argv)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/main/application.py", line 278, in _run
    self.initialize(argv)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/main/application.py", line 269, in initialize
    self.register_plugin_options()
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/main/application.py", line 149, in register_plugin_options
    self.check_plugins.register_options(self.option_manager)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/plugins/manager.py", line 378, in register_options
    list(self.manager.map(call_register_options))
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/plugins/manager.py", line 252, in map
    yield func(self.plugins[name], *args, **kwargs)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/plugins/manager.py", line 348, in generated_function
    return method(optmanager, *args, **kwargs)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/flake8/plugins/manager.py", line 198, in register_options
    add_options(optmanager)
  File "/home/havok/Hacking/plantweb/.tox/py34/lib/python3.4/site-packages/pep8ext_naming.py", line 78, in add_options
    parser.config_options.append('ignore-names')
AttributeError: 'OptionManager' object has no attribute 'config_options'

Falling back to flake8 2.6.2 allows to continue using the extension.

Regards.

N803 argument name '_' should be lowercase

After upgrading to pep8-naming 0.8.0 , we started seeing this error

N803 argument name '_' should be lowercase

This is a problem with pep8-naming, as _ lowercase is _.

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

ignore-names does not apply for all checks

Unless I'm missing something, the ignore argument to the visitor methods is used only in FunctionNameCheck (N802). Is this by design? Would be great to apply this option for all checks.

N812 false positive for gettext(_lazy) as _ (underscore)

With the recent release of pep8-naming I suddenly get a lot of N812 errors related to the import of gettext (and gettext_lazy in a Django project) as _ (underscore).

N812 lowercase 'gettext_lazy' imported as non lowercase '_'

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.

Option (or documentation) for preferring camelCase to underscore_words

I'd really like to extend my Travis CI stylistic consistency checks to also cover naming
but, for a variety of reasons (length, taste, etc.), I'm not willing to switch my codebases over
to underscore_words style for function and argument names.

How difficult would it be to extend (or document) pep8-naming so I can specify such a
preference in my tox.ini without having to maintain a fork of pep8-naming?

crash with tuple function argument

It crashes on this code (Python 2.7):

def f4(two, (compound, (argument, list))): pass

Traceback:

Traceback (most recent call last):
  File "bin/flint", line 9, in <module>
    load_entry_point('flint==0.2a0', 'console_scripts', 'flint')()
  File "flint/flint/__init__.py", line 66, in main
    report = flint_style.check_files()
  File "lib/python2.7/site-packages/pep8.py", line 1609, in check_files
    runner(path)
  File "lib/python2.7/site-packages/pep8.py", line 1618, in input_file
    return fchecker.check_all(expected=expected, line_offset=line_offset)
  File "lib/python2.7/site-packages/pep8.py", line 1358, in check_all
    self.check_ast()
  File "lib/python2.7/site-packages/pep8.py", line 1338, in check_ast
    for lineno, offset, text, check in checker.run():
  File "flint_naming/flint_naming.py", line 72, in visit_tree
    for error in self.visit_tree(child):
  File "flint_naming/flint_naming.py", line 68, in visit_tree
    for error in self.visit_node(node):
  File "flint_naming/flint_naming.py", line 86, in visit_node
    for error in getattr(visitor, method)(node, self.parents):
  File "flint_naming/flint_naming.py", line 190, in visit_functiondef
    arg_names = get_arg_names(node)
  File "flint_naming/flint_naming.py", line 22, in get_arg_names
    ret.append(t_arg.id)
AttributeError: 'Tuple' object has no attribute 'id'

False positive N805 on overriden __new__ method

Description

Overriden new methods are always static methods and their first parameter should not be named self, but pep8-naming prints an error when it is not self.

How to replicate:

$ cat new_override.py 
class NewOverride(object):
    def __new__(cls):
        return object.__new__(NewOverride)
$ flake8 new_override.py 
new_override.py:2:9: N805 first argument of a method should be named 'self'

Support `async` functions and method

Currently this extensions does not support AsyncFunctionDef.
And does not check anything in it unlike in normal FunctionDef.

I guess this should be addressed, since many people use async and it is a part of the language.

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!

N807 false-positive for conditionally created methods

# sample.py
import sys


class C:

    if sys.version_info[0] == 2:
        def __unicode__(self):
            return 'unicode'
    else:
        def __str__(self):
            return 'str'
$ flake8.exe sample.py
sample.py:7:13: N807 function name '__str__' should not start or end with '__'
sample.py:10:13: N807 function name '__unicode__' should not start or end with '__'

Add constants naming rules

pep8 implies that constants are named in UPPER_CASE: https://www.python.org/dev/peps/pep-0008/#constants

Right now this code is considered valid:

# Module-level variable:
delta = 10

However, it is not valid. This one is:

# Module-level variable:
DELTA = 10

pylint has checks for it: C: 8, 0: Constant name "delta" doesn't conform to UPPER_CASE naming style (invalid-name)

Loop variables not detected

def test(values):
    """Test naming conventions."""
    for myValue in values:
        print(myValue)

Does not create any warnings, but

def test(values):
    """Test namining conventions."""
    myValue = None
    for myValue in values:
        print(myValue)

results in

test.py:6:5: N806 variable 'myValue' in function should be lowercase

AttributeError: 'Tuple' object has no attribute 'id'

Just picked up version 0.8.0 and started seeing the following tracebacks when running flake8:

Traceback (most recent call last):
  File "/opt/stackstorm/virtualenvs/stackstorm/bin/flake8", line 11, in <module>
    sys.exit(main())
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/cli.py", line 16, in main
    app.run(argv)
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 396, in run
    self._run(argv)
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 384, in _run
    self.run_checks()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 310, in run_checks
    self.file_checker_manager.run()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 319, in run
    self.run_parallel()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 288, in run_parallel
    for ret in pool_map:
  File "/opt/plexxi/python/lib/python2.7/multiprocessing/pool.py", line 289, in <genexpr>
    return (item for chunk in result for item in chunk)
  File "/opt/plexxi/python/lib/python2.7/multiprocessing/pool.py", line 673, in next
    raise value
AttributeError: 'Tuple' object has no attribute 'id' 

I made the following modifications to lib/python2.7/site-packages/pep8ext_naming.py to get more details:

Starting at line 462 of pep8ext_naming.py:

        if PY2:
            + print 'Target:', assignment_target.__dict__
            + try:
                 yield assignment_target.name.id
            + except Exception as e:
            +    print 'Name._fields', assignment_target.name._fields
            +    print 'Name.elts', assignment_target.name.elts
            +    print 'Name.ctx', assignment_target.name.ctx
            +   raise e
        else:
            yield assignment_target.name
        return

And ran in single-threaded mode:
flake8 /src -j 1

Now seeing:

Target: {'body': [<_ast.Assign object at 0x7fd25eafecd0>, <_ast.Expr object at 0x7fd25eafed90>, <_ast.Expr object at 0x7fd25eafefd0>, <_ast.Continue object at 0x7fd25eaee210>], 'name': <_ast.Name object at 0x7fd25eafec90>, 'col_offset': 12, 'depth': 3, 'parent': <_ast.TryExcept object at 0x7fd25eae4990>, 'lineno': 248, 'type': <_ast.Name object at 0x7fd25eafec50>}
Target: {'body': [<_ast.Assign object at 0x7fd25ea8e050>, <_ast.Return object at 0x7fd25ea8e210>], 'name': <_ast.Tuple object at 0x7fd25eaadf50>, 'col_offset': 12, 'depth': 3, 'parent': <_ast.TryExcept object at 0x7fd25eaad5d0>, 'lineno': 363, 'type': <_ast.Tuple object at 0x7fd25eaade10>}
Name._fields ('elts', 'ctx')
Name.elts [<_ast.Name object at 0x7fd25eaadf90>, <_ast.Name object at 0x7fd25eaadfd0>]
Name.ctx <_ast.Store object at 0x7fd25f12ad90>
Traceback (most recent call last):
  File "/opt/stackstorm/virtualenvs/stackstorm/bin/flake8", line 11, in <module>
    sys.exit(main())
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/cli.py", line 16, in main
    app.run(argv)
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 396, in run
    self._run(argv)
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 384, in _run
    self.run_checks()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/main/application.py", line 310, in run_checks
    self.file_checker_manager.run()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 321, in run
    self.run_serial()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 305, in run_serial
    checker.run_checks()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 579, in run_checks
    self.run_ast_checks()
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/flake8/checker.py", line 493, in run_ast_checks
    for (line_number, offset, text, check) in runner:
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 158, in visit_tree
    for error in self.visit_tree(child):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 158, in visit_tree
    for error in self.visit_tree(child):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 158, in visit_tree
    for error in self.visit_tree(child):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 158, in visit_tree
    for error in self.visit_tree(child):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 158, in visit_tree
    for error in self.visit_tree(child):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 154, in visit_tree
    for error in self.visit_node(node):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 175, in visit_node
    for error in visitor_method(node, parents, ignore_names):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 413, in visit_excepthandler
    for error in self._find_errors(node, parents):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 377, in _find_errors
    for name in _extract_names(assignment_target):
  File "/opt/stackstorm/virtualenvs/stackstorm/lib/python2.7/site-packages/pep8ext_naming.py", line 469, in _extract_names
    raise e
AttributeError: 'Tuple' object has no attribute 'id'

Using versions:

[root@3cc3a5f9a39b ~]# pip list | grep flake8
flake8                             3.5.0
flake8-blind-except                0.1.1
flake8-builtins                    1.1.1
flake8-copyright                   0.2.2
flake8-docstrings                  1.3.0
flake8-future-import               0.4.5
flake8-import-order                0.18
flake8-pep3101                     1.2.1
flake8-polyfill                    1.0.2
flake8-print                       3.1.0
flake8-quotes                      1.0.0
flake8-string-format               0.2.3
You are using pip version 18.1, however version 19.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.


[root@3cc3a5f9a39b ~]# flake8 --version
3.5.0 (flake8-blind-except: 0.1.1, flake8-docstrings: 1.3.0, pydocstyle: 3.0.0, flake8-future-import: 0.4.5, flake8-print: 3.1.0, flake8-string-format: 0.2.3, flake8_builtins: 0.3, flake8_copyright: 0.2.2, flake8_pep3101: 1.2.1, flake8_quotes: 1.0.0, import-order: 0.18, mccabe: 0.6.1, naming: 0.8.0, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 2.7.15 on Linux

Reverting to version pep8-naming==0.7.0 works fine.

N806 not thrown for multiple assignment

I have a line of code that looks like the following, for which I would expect two N806 errors:

(minYear, maxYear) = some_function_here()

The names minYear and maxYear both violate the pep-8 naming rules, but no errors are generated.

Allow methods starting with "assert"

When using unittest, I tend to name custom assertion methods using camelCase.

I tried setting ignore-names to include assert* but that didn't do what I'd hoped. If there was a way to specify a glob or regular expression in ignore-names, that would allow me to accept all methods starting with assert as valid.

metaclasses and functions returning classes

python is a dynamic language. functions may return classes, and instantiating metaclasses also yields classes.

since we can’t know what a function returns, VariablesInFunctionCheck should not yield an error if a variable name matches MIXEDCASE_REGEX, e.g.:

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)

False Positive: unittest.TestCase.setUp

When making unit tests using the built-in unittest module, python defines a setUp method for unittest.TestCase that is used to do standard setup operations for all tests. Users have to override this method, and thus use this name, to do the setup, but pep8-naming nevertheless flags it as violating N802 function name should be lowercase. Since it is something in the standard library that users have no control over, it shouldn't violate the rule.

N806 Constant inside function false positive

Accroding to PEP8, constants inside functions/method are not forbidden.

Following case fails test

class TestCase:
    def test_data:
        DATASET = {...}
        ... DATASET usage (may be multiple times)

'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)?

Add test for bad assignments (to self/cls)

See this as an example of implementation. This will catch code like

class A:
    def foo(self, arg):
        self = arg

or

class A(object):
    @classmethod
    def foo(cls, arg):
        cls = arg

Yes, this is not a PEP 8 requirement, but there is some wrong if I should introduce new extension for naming tests just for that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.