Skip to content

Commit 62802c8

Browse files
committed
Enable ruff N ruleset for pep8 naming conventions
1 parent 88e31eb commit 62802c8

File tree

14 files changed

+53
-65
lines changed

14 files changed

+53
-65
lines changed

cmd2/argparse_custom.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -883,7 +883,7 @@ def _match_argument_wrapper(self: argparse.ArgumentParser, action: argparse.Acti
883883
ATTR_AP_COMPLETER_TYPE = 'ap_completer_type'
884884

885885

886-
def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Optional[type['ArgparseCompleter']]:
886+
def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Optional[type['ArgparseCompleter']]: # noqa: N802
887887
"""Get the ap_completer_type attribute of an argparse ArgumentParser.
888888
889889
This function is added by cmd2 as a method called ``get_ap_completer_type()`` to ``argparse.ArgumentParser`` class.
@@ -899,7 +899,7 @@ def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Opti
899899
setattr(argparse.ArgumentParser, 'get_ap_completer_type', _ArgumentParser_get_ap_completer_type)
900900

901901

902-
def _ArgumentParser_set_ap_completer_type(self: argparse.ArgumentParser, ap_completer_type: type['ArgparseCompleter']) -> None:
902+
def _ArgumentParser_set_ap_completer_type(self: argparse.ArgumentParser, ap_completer_type: type['ArgparseCompleter']) -> None: # noqa: N802
903903
"""Set the ap_completer_type attribute of an argparse ArgumentParser.
904904
905905
This function is added by cmd2 as a method called ``set_ap_completer_type()`` to ``argparse.ArgumentParser`` class.
@@ -918,7 +918,7 @@ def _ArgumentParser_set_ap_completer_type(self: argparse.ArgumentParser, ap_comp
918918
############################################################################################################
919919
# Patch ArgumentParser._check_value to support CompletionItems as choices
920920
############################################################################################################
921-
def _ArgumentParser_check_value(self: argparse.ArgumentParser, action: argparse.Action, value: Any) -> None:
921+
def _ArgumentParser_check_value(self: argparse.ArgumentParser, action: argparse.Action, value: Any) -> None: # noqa: N802
922922
"""Custom override of ArgumentParser._check_value that supports CompletionItems as choices.
923923
When evaluating choices, input is compared to CompletionItem.orig_value instead of the
924924
CompletionItem instance.
@@ -950,7 +950,7 @@ def _ArgumentParser_check_value(self: argparse.ArgumentParser, action: argparse.
950950
############################################################################################################
951951

952952

953-
def _SubParsersAction_remove_parser(self: argparse._SubParsersAction, name: str) -> None: # type: ignore[type-arg]
953+
def _SubParsersAction_remove_parser(self: argparse._SubParsersAction, name: str) -> None: # type: ignore[type-arg] # noqa: N802
954954
"""Removes a sub-parser from a sub-parsers group. Used to remove subcommands from a parser.
955955
956956
This function is added by cmd2 as a method called ``remove_parser()`` to ``argparse._SubParsersAction`` class.

cmd2/cmd2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1973,7 +1973,7 @@ def _determine_ap_completer_type(parser: argparse.ArgumentParser) -> type[argpar
19731973
:param parser: the parser to examine
19741974
:return: type of ArgparseCompleter
19751975
"""
1976-
Completer = Optional[type[argparse_completer.ArgparseCompleter]]
1976+
Completer = Optional[type[argparse_completer.ArgparseCompleter]] # noqa: N806
19771977
completer_type: Completer = parser.get_ap_completer_type() # type: ignore[attr-defined]
19781978

19791979
if completer_type is None:
@@ -4528,7 +4528,7 @@ def do_ipy(self, _: argparse.Namespace) -> Optional[bool]: # pragma: no cover
45284528

45294529
# Detect whether IPython is installed
45304530
try:
4531-
import traitlets.config.loader as TraitletsLoader # type: ignore[import]
4531+
import traitlets.config.loader as traitlets_loader # type: ignore[import]
45324532

45334533
# Allow users to install ipython from a cmd2 prompt when needed and still have ipy command work
45344534
try:
@@ -4569,7 +4569,7 @@ def do_ipy(self, _: argparse.Namespace) -> Optional[bool]: # pragma: no cover
45694569
local_vars['self'] = self
45704570

45714571
# Configure IPython
4572-
config = TraitletsLoader.Config()
4572+
config = traitlets_loader.Config()
45734573
config.InteractiveShell.banner2 = (
45744574
'Entering an IPython shell. Type exit, quit, or Ctrl-D to exit.\n'
45754575
f'Run CLI commands with: {self.py_bridge_name}("command ...")\n'

cmd2/exceptions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
############################################################################################################
88

99

10-
class SkipPostcommandHooks(Exception):
10+
class SkipPostcommandHooks(Exception): # noqa: N818
1111
"""Custom exception class for when a command has a failure bad enough to skip post command
1212
hooks, but not bad enough to print the exception to the user.
1313
"""
@@ -50,7 +50,7 @@ def __init__(self, *args: Any, apply_style: bool = True) -> None:
5050
super().__init__(*args)
5151

5252

53-
class PassThroughException(Exception):
53+
class PassThroughException(Exception): # noqa: N818
5454
"""Normally all unhandled exceptions raised during commands get printed to the user.
5555
This class is used to wrap an exception that should be raised instead of printed.
5656
"""
@@ -76,7 +76,7 @@ class EmbeddedConsoleExit(SystemExit):
7676
"""Custom exception class for use with the py command."""
7777

7878

79-
class EmptyStatement(Exception):
79+
class EmptyStatement(Exception): # noqa: N818
8080
"""Custom exception class for handling behavior when the user just presses <Enter>."""
8181

8282

cmd2/rl_utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,24 +72,24 @@ def enable_win_vt100(handle: HANDLE) -> bool:
7272
:param handle: the handle on which to enable vt100
7373
:return: True if vt100 characters are enabled for the handle.
7474
"""
75-
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
75+
enable_virtual_terminal_processing = 0x0004
7676

7777
# Get the current mode for this handle in the console
7878
cur_mode = DWORD(0)
7979
readline.rl.console.GetConsoleMode(handle, byref(cur_mode))
8080

81-
retVal = False
81+
ret_val = False
8282

8383
# Check if ENABLE_VIRTUAL_TERMINAL_PROCESSING is already enabled
84-
if (cur_mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0:
85-
retVal = True
84+
if (cur_mode.value & enable_virtual_terminal_processing) != 0:
85+
ret_val = True
8686

87-
elif readline.rl.console.SetConsoleMode(handle, cur_mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING):
87+
elif readline.rl.console.SetConsoleMode(handle, cur_mode.value | enable_virtual_terminal_processing):
8888
# Restore the original mode when we exit
8989
atexit.register(readline.rl.console.SetConsoleMode, handle, cur_mode)
90-
retVal = True
90+
ret_val = True
9191

92-
return retVal
92+
return ret_val
9393

9494
# Enable VT100 sequences for stdout and stderr
9595
STD_OUT_HANDLE = -11
@@ -273,10 +273,10 @@ def rl_in_search_mode() -> bool: # pragma: no cover
273273
# GNU Readline defines constants that we can use to determine if in search mode.
274274
# RL_STATE_ISEARCH 0x0000080
275275
# RL_STATE_NSEARCH 0x0000100
276-
IN_SEARCH_MODE = 0x0000180
276+
in_search_mode = 0x0000180
277277

278278
readline_state = ctypes.c_int.in_dll(readline_lib, "rl_readline_state").value
279-
return bool(IN_SEARCH_MODE & readline_state)
279+
return bool(in_search_mode & readline_state)
280280
if rl_type == RlType.PYREADLINE:
281281
from pyreadline3.modes.emacs import ( # type: ignore[import]
282282
EmacsMode,

cmd2/transcript.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class Cmd2TestCase(unittest.TestCase):
4343

4444
def setUp(self) -> None:
4545
if self.cmdapp:
46-
self._fetchTranscripts()
46+
self._fetch_transcripts()
4747

4848
# Trap stdout
4949
self._orig_stdout = self.cmdapp.stdout
@@ -54,13 +54,13 @@ def tearDown(self) -> None:
5454
# Restore stdout
5555
self.cmdapp.stdout = self._orig_stdout
5656

57-
def runTest(self) -> None: # was testall
57+
def runTest(self) -> None: # was testall # noqa: N802
5858
if self.cmdapp:
5959
its = sorted(self.transcripts.items())
6060
for fname, transcript in its:
6161
self._test_transcript(fname, transcript)
6262

63-
def _fetchTranscripts(self) -> None:
63+
def _fetch_transcripts(self) -> None:
6464
self.transcripts = {}
6565
testfiles = cast(list[str], getattr(self.cmdapp, 'testfiles', []))
6666
for fname in testfiles:

examples/migrating.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def do_exit(self, line) -> bool:
1717
"""Exit the application."""
1818
return True
1919

20-
do_EOF = do_exit
20+
do_EOF = do_exit # noqa: N815
2121
do_quit = do_exit
2222

2323
def do_speak(self, line) -> None:

examples/override_parser.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@
1212

1313
# Next import from cmd2. It will import your module just before the cmd2.Cmd class file is imported
1414
# and therefore override the parser class it uses on its commands.
15-
from cmd2 import (
16-
cmd2,
17-
)
15+
from cmd2 import cmd2 # noqa: E402
1816

1917
if __name__ == '__main__':
2018
import sys

examples/unicode_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@ def __init__(self) -> None:
1313
super().__init__()
1414
self.intro = 'Welcome the Unicode example app. Note the full Unicode support: 😇 💩'
1515

16-
def do_𝛑print(self, _) -> None:
16+
def do_𝛑print(self, _) -> None: # noqa: PLC2401
1717
"""This command prints 𝛑 to 5 decimal places."""
1818
self.poutput(f"𝛑 = {math.pi:.6}")
1919

20-
def do_你好(self, arg) -> None:
20+
def do_你好(self, arg) -> None: # noqa: N802, PLC2401
2121
"""This command says hello in Chinese (Mandarin)."""
2222
self.poutput("你好 " + arg)
2323

plugins/ext_test/tasks.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,15 @@ def rmrf(items, verbose=True):
4848
@invoke.task
4949
def pytest(context, junit=False, pty=True, append_cov=False):
5050
"""Run tests and code coverage using pytest"""
51-
ROOT_PATH = TASK_ROOT.parent.parent
51+
root_path = TASK_ROOT.parent.parent
5252

53-
with context.cd(str(ROOT_PATH)):
53+
with context.cd(str(root_path)):
5454
command_str = 'pytest --cov=cmd2_ext_test --cov-report=term --cov-report=html'
5555
if append_cov:
5656
command_str += ' --cov-append'
5757
if junit:
5858
command_str += ' --junitxml=junit/test-results.xml'
59-
command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH))
59+
command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(root_path))
6060
context.run(command_str, pty=pty)
6161

6262

plugins/template/tasks.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ def rmrf(items, verbose=True) -> None:
4141
@invoke.task
4242
def pytest(context, junit=False, pty=True, append_cov=False) -> None:
4343
"""Run tests and code coverage using pytest."""
44-
ROOT_PATH = TASK_ROOT.parent.parent
44+
root_path = TASK_ROOT.parent.parent
4545

46-
with context.cd(str(ROOT_PATH)):
46+
with context.cd(str(root_path)):
4747
command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html'
4848
if append_cov:
4949
command_str += ' --cov-append'
5050
if junit:
5151
command_str += ' --junitxml=junit/test-results.xml'
52-
command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH))
52+
command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(root_path))
5353
context.run(command_str, pty=pty)
5454

5555

pyproject.toml

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ select = [
189189
"INT", # flake8-gettext (warnings that only apply when you are internationalizing your strings)
190190
"ISC", # flake8-implicit-str-concat (warnings related to implicit vs explicit string concatenation)
191191
"LOG", # flake8-logging (warn about potential logger issues, but very pedantic)
192-
# "N", # pep8-naming (force idiomatic naming for classes, functions/methods, and variables/arguments)
192+
"N", # pep8-naming (force idiomatic naming for classes, functions/methods, and variables/arguments)
193193
# "NPY", # NumPy specific rules
194194
# "PD", # pandas-vet (Pandas specific rules)
195195
"PERF", # Perflint (warn about performance issues)
@@ -260,6 +260,10 @@ per-file-ignores."cmd2/argparse_custom.py" = [
260260
"UP031", # Use format specifiers instead of percent format (auto fix is unsafe)
261261
]
262262

263+
per-file-ignores."cmd2/ansi.py" = [
264+
"N802", # Function names should be lowercase for things like Curor.UP
265+
]
266+
263267
per-file-ignores."examples/*.py" = [
264268
"ANN", # Ignore all type annotation rules in examples folder
265269
"D", # Ignore all pydocstyle rules in examples folder
@@ -268,18 +272,10 @@ per-file-ignores."examples/*.py" = [
268272
"S", # Ignore all Security rules in examples folder
269273
]
270274

271-
per-file-ignores."examples/override_parser.py" = [
272-
"E402", # Module level import not at top of file
273-
]
274-
275275
per-file-ignores."examples/scripts/*.py" = [
276276
"F821", # Undefined name `app`
277277
]
278278

279-
per-file-ignores."examples/unicode_commands.py" = [
280-
"PLC2401", # non-ASCII characters in function names
281-
]
282-
283279
per-file-ignores."plugins/*.py" = [
284280
"ANN", # Ignore all type annotation rules in test folders
285281
"D", # Ignore all pydocstyle rules in test folders
@@ -296,10 +292,6 @@ per-file-ignores."tests/*.py" = [
296292
"SLF", # Ignore all warnings about private or protected member access in test folders
297293
]
298294

299-
per-file-ignores."tests/test_argparse.py" = [
300-
"PLW2901", # loop variable overwritten inside loop
301-
]
302-
303295
per-file-ignores."tests/pyscript/*.py" = [
304296
"F821", # Undefined name `app`
305297
"INP001", # Module is part of an implicit namespace
@@ -312,10 +304,6 @@ per-file-ignores."tests_isolated/*.py" = [
312304
"SLF", # Ignore all warnings about private or protected member access in test folders
313305
]
314306

315-
per-file-ignores."tests_isolated/test_commandset/test_commandset.py" = [
316-
"PLW0603", # Using the global statement to update {name} is discouraged
317-
]
318-
319307

320308
[tool.ruff.format]
321309
# Like Black, use double quotes for strings.

tests/test_argparse.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,14 @@ def do_say(self, args, *, keyword_arg: Optional[str] = None) -> None:
4141
"""
4242
words = []
4343
for word in args.words:
44+
modified_word = word
4445
if word is None:
45-
word = ''
46+
modified_word = ''
4647
if args.piglatin:
47-
word = f'{word[1:]}{word[0]}ay'
48+
modified_word = f'{word[1:]}{word[0]}ay'
4849
if args.shout:
49-
word = word.upper()
50-
words.append(word)
50+
modified_word = word.upper()
51+
words.append(modified_word)
5152
repetitions = args.repeat or 1
5253
for i in range(min(repetitions, self.maxrepeats)):
5354
self.stdout.write(' '.join(words))
@@ -96,13 +97,14 @@ def do_speak(self, args, extra, *, keyword_arg: Optional[str] = None) -> None:
9697
"""Repeat what you tell me to."""
9798
words = []
9899
for word in extra:
100+
modified_word = word
99101
if word is None:
100-
word = ''
102+
modified_word = ''
101103
if args.piglatin:
102-
word = f'{word[1:]}{word[0]}ay'
104+
modified_word = f'{word[1:]}{word[0]}ay'
103105
if args.shout:
104-
word = word.upper()
105-
words.append(word)
106+
modified_word = word.upper()
107+
words.append(modified_word)
106108
repetitions = args.repeat or 1
107109
for i in range(min(repetitions, self.maxrepeats)):
108110
self.stdout.write(' '.join(words))

tests/test_cmd2.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,15 @@ def cmd_wrapper(*args, **kwargs):
6161
return arg_decorator
6262

6363

64-
def CreateOutsimApp():
64+
def create_outsim_app():
6565
c = cmd2.Cmd()
6666
c.stdout = utils.StdSim(c.stdout)
6767
return c
6868

6969

7070
@pytest.fixture
7171
def outsim_app():
72-
return CreateOutsimApp()
72+
return create_outsim_app()
7373

7474

7575
def test_version(base_app) -> None:
@@ -976,7 +976,7 @@ def test_base_cmdloop_with_startup_commands() -> None:
976976
expected = intro + '\n'
977977

978978
with mock.patch.object(sys, 'argv', testargs):
979-
app = CreateOutsimApp()
979+
app = create_outsim_app()
980980

981981
app.use_rawinput = True
982982

@@ -991,7 +991,7 @@ def test_base_cmdloop_without_startup_commands() -> None:
991991
# Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
992992
testargs = ["prog"]
993993
with mock.patch.object(sys, 'argv', testargs):
994-
app = CreateOutsimApp()
994+
app = create_outsim_app()
995995

996996
app.use_rawinput = True
997997
app.intro = 'Hello World, this is an intro ...'
@@ -1012,7 +1012,7 @@ def test_cmdloop_without_rawinput() -> None:
10121012
# Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
10131013
testargs = ["prog"]
10141014
with mock.patch.object(sys, 'argv', testargs):
1015-
app = CreateOutsimApp()
1015+
app = create_outsim_app()
10161016

10171017
app.use_rawinput = False
10181018
app.echo = False

tests_isolated/test_commandset/test_commandset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -832,7 +832,7 @@ def do_user_unrelated(self, ns: argparse.Namespace) -> None:
832832

833833

834834
def test_cross_commandset_completer(command_sets_manual, capsys) -> None:
835-
global complete_states_expected_self
835+
global complete_states_expected_self # noqa: PLW0603
836836
# This tests the different ways to locate the matching CommandSet when completing an argparse argument.
837837
# Exercises the 3 cases in cmd2.Cmd._resolve_func_self() which is called during argparse tab completion.
838838

0 commit comments

Comments
 (0)