Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5d8e432

Browse files
picnixzAA-Turner
andauthored
gh-132390: Apply Ruff linting toTools/build (#132391)
---------Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com>
1 parent246ed23 commit5d8e432

16 files changed

+109
-99
lines changed

‎.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ repos:
1111
args:[--exit-non-zero-on-fix]
1212
files:^Lib/test/
1313
-id:ruff
14-
name:Run Ruff (lint) on Tools/build/check_warnings.py
14+
name:Run Ruff (lint) on Tools/build/
1515
args:[--exit-non-zero-on-fix, --config=Tools/build/.ruff.toml]
16-
files:^Tools/build/check_warnings.py
16+
files:^Tools/build/
1717
-id:ruff
1818
name:Run Ruff (lint) on Argument Clinic
1919
args:[--exit-non-zero-on-fix, --config=Tools/clinic/.ruff.toml]

‎Tools/build/.ruff.toml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,22 @@ select = [
1818
"W",# pycodestyle
1919
"YTT",# flake8-2020
2020
]
21+
ignore = [
22+
"E501",# Line too long
23+
"F541",# f-string without any placeholders
24+
"PYI024",# Use `typing.NamedTuple` instead of `collections.namedtuple`
25+
"PYI025",# Use `from collections.abc import Set as AbstractSet`
26+
"UP038",# Use `X | Y` in `isinstance` call instead of `(X, Y)`
27+
]
28+
29+
[per-file-target-version]
30+
"deepfreeze.py" ="py310"
31+
"stable_abi.py" ="py311"# requires 'tomllib'
32+
33+
[lint.per-file-ignores]
34+
"{check_extension_modules,freeze_modules}.py" = [
35+
"UP031",# Use format specifiers instead of percent format
36+
]
37+
"generate_{re_casefix,sre_constants,token}.py" = [
38+
"UP031",# Use format specifiers instead of percent format
39+
]

‎Tools/build/check_extension_modules.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
1818
See --help for more information
1919
"""
20+
import_imp
2021
importargparse
2122
importcollections
2223
importenum
@@ -27,12 +28,14 @@
2728
importsys
2829
importsysconfig
2930
importwarnings
30-
import_imp
31-
31+
fromcollections.abcimportIterable
3232
fromimportlib._bootstrapimport_loadasbootstrap_load
33-
fromimportlib.machineryimportBuiltinImporter,ExtensionFileLoader,ModuleSpec
33+
fromimportlib.machineryimport (
34+
BuiltinImporter,
35+
ExtensionFileLoader,
36+
ModuleSpec,
37+
)
3438
fromimportlib.utilimportspec_from_file_location,spec_from_loader
35-
fromtypingimportIterable
3639

3740
SRC_DIR=pathlib.Path(__file__).parent.parent.parent
3841

@@ -195,7 +198,7 @@ def print_three_column(modinfos: list[ModuleInfo]):
195198
# guarantee zip() doesn't drop anything
196199
whilelen(names)%3:
197200
names.append("")
198-
forl,m,rinzip(names[::3],names[1::3],names[2::3]):
201+
forl,m,rinzip(names[::3],names[1::3],names[2::3]):# noqa: E741
199202
print("%-*s %-*s %-*s"% (longest,l,longest,m,longest,r))
200203

201204
ifverboseandself.builtin_ok:
@@ -420,7 +423,7 @@ def check_module_import(self, modinfo: ModuleInfo):
420423
exceptImportErrorase:
421424
logger.error("%s failed to import: %s",modinfo.name,e)
422425
raise
423-
exceptExceptionase:
426+
exceptException:
424427
ifnothasattr(_imp,'create_dynamic'):
425428
logger.warning("Dynamic extension '%s' ignored",modinfo.name)
426429
return

‎Tools/build/deepfreeze.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
importre
1414
importtime
1515
importtypes
16-
fromtypingimportDict,FrozenSet,TextIO,Tuple
16+
fromtypingimportTextIO
1717

1818
importumarshal
1919

@@ -57,8 +57,8 @@ def get_localsplus(code: types.CodeType):
5757

5858

5959
defget_localsplus_counts(code:types.CodeType,
60-
names:Tuple[str, ...],
61-
kinds:bytes)->Tuple[int,int,int,int]:
60+
names:tuple[str, ...],
61+
kinds:bytes)->tuple[int,int,int]:
6262
nlocals=0
6363
ncellvars=0
6464
nfreevars=0
@@ -84,7 +84,7 @@ def get_localsplus_counts(code: types.CodeType,
8484
PyUnicode_4BYTE_KIND=4
8585

8686

87-
defanalyze_character_width(s:str)->Tuple[int,bool]:
87+
defanalyze_character_width(s:str)->tuple[int,bool]:
8888
maxchar=' '
8989
forcins:
9090
maxchar=max(maxchar,c)
@@ -109,7 +109,7 @@ class Printer:
109109
def__init__(self,file:TextIO)->None:
110110
self.level=0
111111
self.file=file
112-
self.cache:Dict[tuple[type,object,str],str]= {}
112+
self.cache:dict[tuple[type,object,str],str]= {}
113113
self.hits,self.misses=0,0
114114
self.finis:list[str]= []
115115
self.inits:list[str]= []
@@ -305,7 +305,7 @@ def generate_code(self, name: str, code: types.CodeType) -> str:
305305
self.inits.append(f"_PyStaticCode_Init({name_as_code})")
306306
returnf"&{name}.ob_base.ob_base"
307307

308-
defgenerate_tuple(self,name:str,t:Tuple[object, ...])->str:
308+
defgenerate_tuple(self,name:str,t:tuple[object, ...])->str:
309309
iflen(t)==0:
310310
returnf"(PyObject *)& _Py_SINGLETON(tuple_empty)"
311311
items= [self.generate(f"{name}_{i}",it)fori,itinenumerate(t)]
@@ -379,7 +379,7 @@ def generate_complex(self, name: str, z: complex) -> str:
379379
self.write(f".cval = {{{z.real},{z.imag} }},")
380380
returnf"&{name}.ob_base"
381381

382-
defgenerate_frozenset(self,name:str,fs:FrozenSet[object])->str:
382+
defgenerate_frozenset(self,name:str,fs:frozenset[object])->str:
383383
try:
384384
fs=sorted(fs)
385385
exceptTypeError:
@@ -465,7 +465,7 @@ def generate(args: list[str], output: TextIO) -> None:
465465
printer=Printer(output)
466466
forarginargs:
467467
file,modname=arg.rsplit(':',1)
468-
withopen(file,"r",encoding="utf8")asfd:
468+
withopen(file,encoding="utf8")asfd:
469469
source=fd.read()
470470
ifis_frozen_header(source):
471471
code=decode_frozen_data(source)
@@ -513,7 +513,7 @@ def main() -> None:
513513
ifargs.file:
514514
ifverbose:
515515
print(f"Reading targets from{args.file}")
516-
withopen(args.file,"rt",encoding="utf-8-sig")asfin:
516+
withopen(args.file,encoding="utf-8-sig")asfin:
517517
rules= [x.strip()forxinfin]
518518
else:
519519
rules=args.args

‎Tools/build/freeze_modules.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33
See the notes at the top of Python/frozen.c for more info.
44
"""
55

6-
fromcollectionsimportnamedtuple
76
importhashlib
87
importntpath
98
importos
109
importposixpath
10+
fromcollectionsimportnamedtuple
1111

1212
fromupdate_fileimportupdating_file_with_tmpfile
1313

14-
1514
ROOT_DIR=os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
1615
ROOT_DIR=os.path.abspath(ROOT_DIR)
1716
FROZEN_ONLY=os.path.join(ROOT_DIR,'Tools','freeze','flag.py')
@@ -482,7 +481,6 @@ def regen_frozen(modules):
482481
header=relpath_for_posix_display(src.frozenfile,parentdir)
483482
headerlines.append(f'#include "{header}"')
484483

485-
externlines=UniqueList()
486484
bootstraplines= []
487485
stdliblines= []
488486
testlines= []
@@ -625,7 +623,6 @@ def regen_makefile(modules):
625623
defregen_pcbuild(modules):
626624
projlines= []
627625
filterlines= []
628-
corelines= []
629626
forsrcin_iter_sources(modules):
630627
pyfile=relpath_for_windows_display(src.pyfile,ROOT_DIR)
631628
header=relpath_for_windows_display(src.frozenfile,ROOT_DIR)

‎Tools/build/generate_global_objects.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,8 @@ def generate_runtime_init(identifiers, strings):
286286
break
287287
else:
288288
raiseNotImplementedError
289-
assertnsmallposintsandnsmallnegints
289+
assertnsmallposints
290+
assertnsmallnegints
290291

291292
# Then target the runtime initializer.
292293
filename=os.path.join(INTERNAL,'pycore_runtime_init_generated.h')
@@ -434,7 +435,7 @@ def get_identifiers_and_strings() -> 'tuple[set[str], dict[str, str]]':
434435
# To cover tricky cases (like "\n") we also generate C asserts.
435436
raiseValueError(
436437
'do not use &_Py_ID or &_Py_STR for one-character latin-1 '
437-
+f'strings, use _Py_LATIN1_CHR instead:{string!r}')
438+
f'strings, use _Py_LATIN1_CHR instead:{string!r}')
438439
ifstringnotinstrings:
439440
strings[string]=name
440441
elifname!=strings[string]:

‎Tools/build/generate_levenshtein_examples.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
"""Generate 10,000 unique examples for the Levenshtein short-circuit tests."""
22

33
importargparse
4-
fromfunctoolsimportlru_cache
54
importjson
65
importos.path
6+
fromfunctoolsimportlru_cache
77
fromrandomimportchoices,randrange
88

9-
109
# This should be in sync with Lib/traceback.py. It's not importing those values
1110
# because this script is being executed by PYTHON_FOR_REGEN and not by the in-tree
1211
# build of Python.

‎Tools/build/generate_re_casefix.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
defupdate_file(file,content):
1111
try:
12-
withopen(file,'r',encoding='utf-8')asfobj:
12+
withopen(file,encoding='utf-8')asfobj:
1313
iffobj.read()==content:
1414
returnFalse
1515
except (OSError,ValueError):
@@ -50,7 +50,7 @@ def main(outfile='Lib/re/_casefix.py'):
5050
# List of codes of lowercased characters which have the same uppercase.
5151
equivalent_lower_codes= [sorted(t)
5252
forsinequivalent_chars
53-
fortin [set(ord(c.lower())forcins)]
53+
fortin [{ord(c.lower())forcins}]
5454
iflen(t)>1]
5555

5656
bad_codes= []

‎Tools/build/generate_sbom.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
"""Tool for generating Software Bill of Materials (SBOM) for Python's dependencies"""
2-
importos
3-
importre
2+
3+
importglob
44
importhashlib
55
importjson
6-
importglob
7-
frompathlibimportPath,PurePosixPath,PureWindowsPath
6+
importos
7+
importre
88
importsubprocess
99
importsys
10-
importurllib.request
1110
importtyping
11+
importurllib.request
12+
frompathlibimportPath,PurePosixPath,PureWindowsPath
1213

1314
CPYTHON_ROOT_DIR=Path(__file__).parent.parent.parent
1415

@@ -250,7 +251,7 @@ def check_sbom_packages(sbom_data: dict[str, typing.Any]) -> None:
250251
license_concluded=package["licenseConcluded"]
251252
error_if(
252253
license_concluded!="NOASSERTION",
253-
f"License identifier must be 'NOASSERTION'"
254+
"License identifier must be 'NOASSERTION'"
254255
)
255256

256257

‎Tools/build/generate_sre_constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
defupdate_file(file,content):
88
try:
9-
withopen(file,'r')asfobj:
9+
withopen(file)asfobj:
1010
iffobj.read()==content:
1111
returnFalse
1212
except (OSError,ValueError):

‎Tools/build/generate_stdlib_module_names.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
fromcheck_extension_modulesimportModuleChecker
99

10-
1110
SCRIPT_NAME='Tools/build/generate_stdlib_module_names.py'
1211

1312
SRC_DIR=os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

‎Tools/build/generate_token.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414
importre
1515

16-
1716
SCRIPT_NAME='Tools/build/generate_token.py'
1817
AUTO_GENERATED_BY_SCRIPT=f'Auto-generated by{SCRIPT_NAME}'
1918
NT_OFFSET=256
@@ -46,7 +45,7 @@ def load_tokens(path):
4645

4746
defupdate_file(file,content):
4847
try:
49-
withopen(file,'r')asfobj:
48+
withopen(file)asfobj:
5049
iffobj.read()==content:
5150
returnFalse
5251
except (OSError,ValueError):

‎Tools/build/parse_html5_entities.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@
1212
Written by Ezio Melotti and Iuliia Proskurnia.
1313
"""
1414

15+
importjson
1516
importos
1617
importsys
17-
importjson
18-
fromurllib.requestimporturlopen
1918
fromhtml.entitiesimporthtml5
19+
fromurllib.requestimporturlopen
2020

2121
SCRIPT_NAME='Tools/build/parse_html5_entities.py'
2222
PAGE_URL='https://html.spec.whatwg.org/multipage/named-characters.html'
@@ -40,20 +40,20 @@ def compare_dicts(old, new):
4040
"""Compare the old and new dicts and print the differences."""
4141
added=new.keys()-old.keys()
4242
ifadded:
43-
print('{} entitie(s) have been added:'.format(len(added)))
43+
print(f'{len(added)} entitie(s) have been added:')
4444
fornameinsorted(added):
45-
print(' {!r}: {!r}'.format(name,new[name]))
45+
print(f'{name!r}:{new[name]!r}')
4646
removed=old.keys()-new.keys()
4747
ifremoved:
48-
print('{} entitie(s) have been removed:'.format(len(removed)))
48+
print(f'{len(removed)} entitie(s) have been removed:')
4949
fornameinsorted(removed):
50-
print(' {!r}: {!r}'.format(name,old[name]))
50+
print(f'{name!r}:{old[name]!r}')
5151
changed=set()
5252
fornamein (old.keys()&new.keys()):
5353
ifold[name]!=new[name]:
5454
changed.add((name,old[name],new[name]))
5555
ifchanged:
56-
print('{} entitie(s) have been modified:'.format(len(changed)))
56+
print(f'{len(changed)} entitie(s) have been modified:')
5757
foriteminsorted(changed):
5858
print(' {!r}: {!r} -> {!r}'.format(*item))
5959

@@ -111,5 +111,5 @@ def write_items(entities, file=sys.stdout):
111111
print('The current dictionary is updated.')
112112
else:
113113
compare_dicts(html5,new_html5)
114-
print('Run "./python {0} --patch" to update Lib/html/entities.html '
115-
'or "./python {0} --create" to see the generated''dictionary.'.format(__file__))
114+
print(f'Run "./python{__file__} --patch" to update Lib/html/entities.html '
115+
f'or "./python{__file__} --create" to see the generated dictionary.')

‎Tools/build/smelly.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
importsys
77
importsysconfig
88

9-
109
ALLOWED_PREFIXES= ('Py','_Py')
1110
ifsys.platform=='darwin':
1211
ALLOWED_PREFIXES+= ('__Py',)
@@ -52,8 +51,8 @@ def get_exported_symbols(library, dynamic=False):
5251
ifdynamic:
5352
args.append('--dynamic')
5453
args.append(library)
55-
print("+%s"%' '.join(args))
56-
proc=subprocess.run(args,stdout=subprocess.PIPE,universal_newlines=True)
54+
print(f"+{' '.join(args)}")
55+
proc=subprocess.run(args,stdout=subprocess.PIPE,encoding='utf-8')
5756
ifproc.returncode:
5857
sys.stdout.write(proc.stdout)
5958
sys.exit(proc.returncode)
@@ -80,7 +79,7 @@ def get_smelly_symbols(stdout, dynamic=False):
8079

8180
symtype=parts[1].strip()
8281
symbol=parts[-1]
83-
result='%s (type:%s)'% (symbol,symtype)
82+
result=f'{symbol} (type:{symtype})'
8483

8584
if (symbol.startswith(ALLOWED_PREFIXES)or
8685
symbolinEXCEPTIONSor
@@ -111,10 +110,10 @@ def check_library(library, dynamic=False):
111110
print()
112111
smelly_symbols.sort()
113112
forsymbolinsmelly_symbols:
114-
print("Smelly symbol:%s"%symbol)
113+
print(f"Smelly symbol:{symbol}")
115114

116115
print()
117-
print("ERROR: Found%s smelly symbols!"%len(smelly_symbols))
116+
print(f"ERROR: Found{len(smelly_symbols)} smelly symbols!")
118117
returnlen(smelly_symbols)
119118

120119

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp