diff --git a/mesonbuild/arglist.py b/mesonbuild/arglist.py index 54d7157e2ccf..9ff0945dacb2 100644 --- a/mesonbuild/arglist.py +++ b/mesonbuild/arglist.py @@ -225,10 +225,7 @@ def to_native(self, copy: bool = False) -> T.List[str]: # needed by static libraries that are provided by object files or # shared libraries. self.flush_pre_post() - if copy: - new = self.copy() - else: - new = self + new = self.copy() if copy else self return self.compiler.unix_args_to_native(new._container) def append_direct(self, arg: str) -> None: diff --git a/mesonbuild/ast/interpreter.py b/mesonbuild/ast/interpreter.py index 15d279350eaa..6857529fb562 100644 --- a/mesonbuild/ast/interpreter.py +++ b/mesonbuild/ast/interpreter.py @@ -405,10 +405,7 @@ def quick_resolve(n: BaseNode, loop_detect: T.Optional[T.List[str]] = None) -> T def flatten_args(self, args_raw: T.Union[TYPE_var, T.Sequence[TYPE_var]], include_unknown_args: bool = False, id_loop_detect: T.Optional[T.List[str]] = None) -> T.List[TYPE_var]: # Make sure we are always dealing with lists - if isinstance(args_raw, list): - args = args_raw - else: - args = [args_raw] + args = args_raw if isinstance(args_raw, list) else [args_raw] flattened_args: T.List[TYPE_var] = [] diff --git a/mesonbuild/backend/backends.py b/mesonbuild/backend/backends.py index 9b26d9e6caf5..cd6710afb5d8 100644 --- a/mesonbuild/backend/backends.py +++ b/mesonbuild/backend/backends.py @@ -324,10 +324,7 @@ def get_target_debug_filename_abs(self, target: build.BuildTarget) -> T.Optional def get_source_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]: curdir = target.get_subdir() - if absolute_path: - lead = self.source_dir - else: - lead = self.build_to_src + lead = self.source_dir if absolute_path else self.build_to_src tmppath = os.path.normpath(os.path.join(lead, curdir)) return compiler.get_include_args(tmppath, False) @@ -506,10 +503,7 @@ def _flatten_object_list(self, target: build.BuildTarget, @staticmethod def is_swift_target(target: build.BuildTarget) -> bool: - for s in target.sources: - if s.endswith('swift'): - return True - return False + return any(s.endswith('swift') for s in target.sources) def determine_swift_dep_dirs(self, target: build.BuildTarget) -> T.List[str]: result: T.List[str] = [] @@ -708,10 +702,7 @@ def determine_linker_and_stdlib_args(self, target: build.BuildTarget) -> T.Tuple @staticmethod def _libdir_is_system(libdir: str, compilers: T.Mapping[str, 'Compiler'], env: 'Environment') -> bool: libdir = os.path.normpath(libdir) - for cc in compilers.values(): - if libdir in cc.get_library_dirs(env): - return True - return False + return any(libdir in cc.get_library_dirs(env) for cc in compilers.values()) def get_external_rpath_dirs(self, target: build.BuildTarget) -> T.Set[str]: args: T.List[str] = [] diff --git a/mesonbuild/backend/ninjabackend.py b/mesonbuild/backend/ninjabackend.py index 65f6ea1958af..a5622656506f 100644 --- a/mesonbuild/backend/ninjabackend.py +++ b/mesonbuild/backend/ninjabackend.py @@ -121,10 +121,7 @@ def get_rsp_threshold() -> int: NINJA_QUOTE_VAR_PAT = re.compile(r"[$ \n]") def ninja_quote(text: str, is_build_line: bool = False) -> str: - if is_build_line: - quote_re = NINJA_QUOTE_BUILD_PAT - else: - quote_re = NINJA_QUOTE_VAR_PAT + quote_re = NINJA_QUOTE_BUILD_PAT if is_build_line else NINJA_QUOTE_VAR_PAT # Fast path for when no quoting is necessary if not quote_re.search(text): return text @@ -295,10 +292,7 @@ def length_estimate(self, infiles: str, outfiles: str, if m.start(1) != -1: estimate -= m.end(1) - m.start(1) chunk = m.group(1) - if chunk[1] == '{': - chunk = chunk[2:-1] - else: - chunk = chunk[1:] + chunk = chunk[2:-1] if chunk[1] == '{' else chunk[1:] chunk = ninja_vars.get(chunk, []) # undefined ninja variables are empty estimate += len(' '.join(chunk)) @@ -960,7 +954,7 @@ def generate_target(self, target): # This will be set as dependencies of all the target's sources. At the # same time, also deal with generated sources that need to be compiled. generated_source_files: T.List[File] = [] - for rel_src in generated_sources.keys(): + for rel_src in generated_sources: raw_src = File.from_built_relative(rel_src) if self.environment.is_source(rel_src): if is_unity and self.get_target_source_can_unity(target, rel_src): @@ -1100,9 +1094,7 @@ def should_use_dyndeps_for_target(self, target: 'build.BuildTarget') -> bool: return False if not mesonlib.current_vs_supports_modules(): return False - if mesonlib.version_compare(cpp.version, '<19.28.28617'): - return False - return True + return not mesonlib.version_compare(cpp.version, '<19.28.28617') def generate_dependency_scan_target(self, target: build.BuildTarget, compiled_sources: T.List[str], @@ -1180,10 +1172,7 @@ def generate_custom_target(self, target: build.CustomTarget): deps += self.get_target_depend_files(target) if target.build_always_stale: deps.append('PHONY') - if target.depfile is None: - rulename = 'CUSTOM_COMMAND' - else: - rulename = 'CUSTOM_COMMAND_DEP' + rulename = 'CUSTOM_COMMAND' if target.depfile is None else 'CUSTOM_COMMAND_DEP' elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs) elem.add_dep(deps) for d in target.extra_depends: @@ -1197,10 +1186,7 @@ def generate_custom_target(self, target: build.CustomTarget): feed=srcs[0] if target.feed else None, env=target.env, verbose=target.console) - if reason: - cmd_type = f' (wrapped by meson {reason})' - else: - cmd_type = '' + cmd_type = f' (wrapped by meson {reason})' if reason else '' if target.depfile is not None: depfile = target.get_dep_outname(elem.infilenames) rel_dfile = os.path.join(self.get_target_dir(target), depfile) @@ -1216,10 +1202,7 @@ def generate_custom_target(self, target: build.CustomTarget): self.processed_targets.add(target.get_id()) def build_run_target_name(self, target): - if target.subproject != '': - subproject_prefix = f'{target.subproject}@@' - else: - subproject_prefix = '' + subproject_prefix = f'{target.subproject}@@' if target.subproject != '' else '' return f'{subproject_prefix}{target.name}' def generate_run_target(self, target: build.RunTarget): @@ -1426,7 +1409,7 @@ def generate_jar_target(self, target: build.Jar): # Add possible java generated files to src list generated_sources = self.get_target_generated_sources(target) gen_src_list = [] - for rel_src in generated_sources.keys(): + for rel_src in generated_sources: raw_src = File.from_built_relative(rel_src) if rel_src.endswith('.java'): gen_src_list.append(raw_src) @@ -1513,7 +1496,7 @@ def generate_cs_target(self, target: build.BuildTarget): outputs = [outname_rel] generated_sources = self.get_target_generated_sources(target) generated_rel_srcs = [] - for rel_src in generated_sources.keys(): + for rel_src in generated_sources: if rel_src.lower().endswith('.cs'): generated_rel_srcs.append(os.path.normpath(rel_src)) deps.append(os.path.normpath(rel_src)) @@ -1547,7 +1530,7 @@ def determine_java_compile_args(self, target, compiler): def generate_java_compile(self, srcs, target, compiler, args): deps = [os.path.join(self.get_target_dir(l), l.get_filename()) for l in target.link_targets] generated_sources = self.get_target_generated_sources(target) - for rel_src in generated_sources.keys(): + for rel_src in generated_sources: if rel_src.endswith('.java'): deps.append(rel_src) @@ -2218,10 +2201,7 @@ def generate_swift_target(self, target): for i in reversed(target.get_include_dirs()): basedir = i.get_curdir() for d in i.get_incdirs(): - if d not in ('', '.'): - expdir = os.path.join(basedir, d) - else: - expdir = basedir + expdir = basedir if d in {'', '.'} else os.path.join(basedir, d) srctreedir = os.path.normpath(os.path.join(self.environment.get_build_dir(), self.build_to_src, expdir)) sargs = swiftc.get_include_args(srctreedir, False) compile_args += sargs @@ -2336,10 +2316,7 @@ def generate_static_link_rules(self): ranlib = ['ranlib'] cmdlist.extend(['&&'] + ranlib + ['-c', '$out']) description = 'Linking static target $out' - if num_pools > 0: - pool = 'pool = link_pool' - else: - pool = None + pool = 'pool = link_pool' if num_pools > 0 else None options = self._rsp_options(static_linker) self.add_rule(NinjaRule(rule, cmdlist, args, description, **options, extra=pool)) @@ -2355,10 +2332,7 @@ def generate_dynamic_link_rules(self): command = compiler.get_linker_exelist() args = ['$ARGS'] + NinjaCommandArg.list(compiler.get_linker_output_args('$out'), Quoting.none) + ['$in', '$LINK_ARGS'] description = 'Linking target $out' - if num_pools > 0: - pool = 'pool = link_pool' - else: - pool = None + pool = 'pool = link_pool' if num_pools > 0 else None options = self._rsp_options(compiler) self.add_rule(NinjaRule(rule, command, args, description, **options, extra=pool)) @@ -2450,10 +2424,7 @@ def generate_fortran_dep_hack(self, crstr: str) -> None: if self.use_dyndeps_for_fortran(): return rule = f'FORTRAN_DEP_HACK{crstr}' - if mesonlib.is_windows(): - cmd = ['cmd', '/C'] - else: - cmd = ['true'] + cmd = ['cmd', '/C'] if mesonlib.is_windows() else ['true'] self.add_rule_comment(NinjaComment('''Workaround for these issues: https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485''')) @@ -2932,7 +2903,7 @@ def generate_common_compile_args_per_src_type(self, target: build.BuildTarget) - use_pch = self.target_uses_pch(target) - for src_type_str in target.compilers.keys(): + for src_type_str in target.compilers: compiler = target.compilers[src_type_str] commands = self._generate_single_compile_base_args(target, compiler) diff --git a/mesonbuild/backend/vs2010backend.py b/mesonbuild/backend/vs2010backend.py index a12963cdee06..38d3a463cec0 100644 --- a/mesonbuild/backend/vs2010backend.py +++ b/mesonbuild/backend/vs2010backend.py @@ -296,8 +296,7 @@ def get_vcvars_command(self): # Use vcvarsall.bat if we found it. if 'VCINSTALLDIR' in os.environ: - vs_version = os.environ['VisualStudioVersion'] \ - if 'VisualStudioVersion' in os.environ else None + vs_version = os.environ.get('VisualStudioVersion', None) relative_path = 'Auxiliary\\Build\\' if vs_version is not None and vs_version >= '15.0' else '' script_path = os.environ['VCINSTALLDIR'] + relative_path + 'vcvarsall.bat' if os.path.exists(script_path): @@ -426,7 +425,7 @@ def generate_solution(self, sln_filename: str, projlist: T.List[Project]) -> Non target = self.build.targets[prj[0]] lang = 'default' if hasattr(target, 'compilers') and target.compilers: - for lang_out in target.compilers.keys(): + for lang_out in target.compilers: lang = lang_out break prj_line = prj_templ % ( @@ -870,7 +869,7 @@ def add_project_nmake_defs_incs_and_opts(self, parent_node, src: str, defs_paths # defs/dirs/opts that are set for the nominal 'primary' src type. ext = src.split('.')[-1] lang = compilers.compilers.SUFFIX_TO_LANG.get(ext, None) - if lang in defs_paths_opts_per_lang_and_buildtype.keys(): + if lang in defs_paths_opts_per_lang_and_buildtype: # This is a non-primary src type for which can't simply reference the project's nmake fields; # we must laboriously fill in the fields for all buildtypes. for buildtype in coredata.get_genvs_default_buildtype_list(): @@ -1011,7 +1010,7 @@ def get_args_defines_and_inc_dirs(self, target, compiler, generated_files_includ file_args[l] += args # Compile args added from the env or cross file: CFLAGS/CXXFLAGS, etc. We want these # to override all the defaults, but not the per-target compile args. - for lang in file_args.keys(): + for lang in file_args: file_args[lang] += target.get_option(OptionKey(f'{lang}_args', machine=target.for_machine)) for args in file_args.values(): # This is where Visual Studio will insert target_args, target_defines, @@ -1068,10 +1067,7 @@ def get_args_defines_and_inc_dirs(self, target, compiler, generated_files_includ if arg.startswith(('-D', '/D')) or arg == '%(PreprocessorDefinitions)': file_args[l].remove(arg) # Don't escape the marker - if arg == '%(PreprocessorDefinitions)': - define = arg - else: - define = arg[2:] + define = arg if arg == '%(PreprocessorDefinitions)' else arg[2:] # De-dup if define not in file_defines[l]: file_defines[l].append(define) diff --git a/mesonbuild/build.py b/mesonbuild/build.py index 42f1dcc9c2f9..fe05bd8705fc 100644 --- a/mesonbuild/build.py +++ b/mesonbuild/build.py @@ -2695,9 +2695,7 @@ def is_linkable_output(self, output: str) -> bool: if output.endswith(('.a', '.dll', '.lib', '.so', '.dylib')): return True # libfoo.so.X soname - if re.search(r'\.so(\.\d+)*$', output): - return True - return False + return bool(re.search('\\.so(\\.\\d+)*$', output)) def is_linkable_target(self) -> bool: if len(self.outputs) != 1: diff --git a/mesonbuild/cargo/cfg.py b/mesonbuild/cargo/cfg.py index 0d49527cc2a0..299f82e5be5c 100644 --- a/mesonbuild/cargo/cfg.py +++ b/mesonbuild/cargo/cfg.py @@ -176,9 +176,8 @@ def _parse(ast: _LEX_STREAM_AH) -> IR: ntoken, _ = (None, None) stream: T.List[_LEX_TOKEN] - if token is TokenType.IDENTIFIER: - if ntoken is TokenType.EQUAL: - return Equal(Identifier(value), _parse(ast)) + if token is TokenType.IDENTIFIER and ntoken is TokenType.EQUAL: + return Equal(Identifier(value), _parse(ast)) if token is TokenType.STRING: return String(value) if token is TokenType.EQUAL: diff --git a/mesonbuild/cmake/fileapi.py b/mesonbuild/cmake/fileapi.py index ad371fc8c998..0d45e42df27d 100644 --- a/mesonbuild/cmake/fileapi.py +++ b/mesonbuild/cmake/fileapi.py @@ -319,6 +319,6 @@ def _reply_file_content(self, filename: Path) -> T.Dict[str, T.Any]: data = json.loads(real_path.read_text(encoding='utf-8')) assert isinstance(data, dict) - for i in data.keys(): + for i in data: assert isinstance(i, str) return data diff --git a/mesonbuild/cmake/interpreter.py b/mesonbuild/cmake/interpreter.py index 7071fe4f8a4f..d427248f7025 100644 --- a/mesonbuild/cmake/interpreter.py +++ b/mesonbuild/cmake/interpreter.py @@ -452,9 +452,7 @@ def rel_path(x: Path, is_header: bool, is_generated: bool) -> T.Optional[Path]: def check_flag(flag: str) -> bool: if flag.lower() in BLACKLIST_LINK_FLAGS or flag in BLACKLIST_COMPILER_FLAGS or flag in BLACKLIST_CLANG_CL_LINK_FLAGS: return False - if flag.startswith('/D'): - return False - return True + return not flag.startswith('/D') self.link_libraries = [x for x in self.link_libraries if x.lower() not in BLACKLIST_LINK_LIBS] self.link_flags = [x for x in self.link_flags if check_flag(x)] diff --git a/mesonbuild/cmake/traceparser.py b/mesonbuild/cmake/traceparser.py index 69e4131823fa..4923f4fe7105 100644 --- a/mesonbuild/cmake/traceparser.py +++ b/mesonbuild/cmake/traceparser.py @@ -258,10 +258,7 @@ def var_to_str(self, var: str) -> T.Optional[str]: def _str_to_bool(self, expr: T.Union[str, T.List[str]]) -> bool: if not expr: return False - if isinstance(expr, list): - expr_str = expr[0] - else: - expr_str = expr + expr_str = expr[0] if isinstance(expr, list) else expr expr_str = expr_str.upper() return expr_str not in ['0', 'OFF', 'NO', 'FALSE', 'N', 'IGNORE'] and not expr_str.endswith('NOTFOUND') diff --git a/mesonbuild/compilers/compilers.py b/mesonbuild/compilers/compilers.py index 7057fc2a2662..33ae09eb8a59 100644 --- a/mesonbuild/compilers/compilers.py +++ b/mesonbuild/compilers/compilers.py @@ -772,10 +772,7 @@ def _get_compile_output(self, dirname: str, mode: CompileCheckMode) -> str: assert mode != CompileCheckMode.PREPROCESS, 'In pre-processor mode, the output is sent to stdout and discarded' # Extension only matters if running results; '.exe' is # guaranteed to be executable on every platform. - if mode == CompileCheckMode.LINK: - suffix = 'exe' - else: - suffix = 'obj' + suffix = 'exe' if mode == CompileCheckMode.LINK else 'obj' return os.path.join(dirname, 'output.' + suffix) def get_compiler_args_for_mode(self, mode: CompileCheckMode) -> T.List[str]: diff --git a/mesonbuild/compilers/cs.py b/mesonbuild/compilers/cs.py index 38bb3386672b..d37d8533c61d 100644 --- a/mesonbuild/compilers/cs.py +++ b/mesonbuild/compilers/cs.py @@ -98,10 +98,7 @@ def sanity_check(self, work_dir: str, environment: 'Environment') -> None: pc.wait() if pc.returncode != 0: raise EnvironmentException('C# compiler %s cannot compile programs.' % self.name_string()) - if self.runner: - cmdlist = [self.runner, obj] - else: - cmdlist = [os.path.join(work_dir, obj)] + cmdlist = [self.runner, obj] if self.runner else [os.path.join(work_dir, obj)] pe = subprocess.Popen(cmdlist, cwd=work_dir) pe.wait() if pe.returncode != 0: diff --git a/mesonbuild/compilers/d.py b/mesonbuild/compilers/d.py index d8b252a94668..d0010f1a4139 100644 --- a/mesonbuild/compilers/d.py +++ b/mesonbuild/compilers/d.py @@ -286,10 +286,7 @@ def _translate_args_to_nongnu(cls, args: T.List[str], info: MachineInfo, link_id # The logic that follows tries to detect all these cases (some may be missing) # in order to prepend a -L only for the library search paths with a single -L - if arg.startswith('-L='): - suffix = arg[3:] - else: - suffix = arg[2:] + suffix = arg[3:] if arg.startswith('-L=') else arg[2:] if link_expect_arg: # flags like rpath and soname expect a path or filename respectively, @@ -529,10 +526,7 @@ def get_feature_args(self, kwargs: DFeatures, build_to_src: str) -> T.List[str]: for idir in idir_obj.get_incdirs(): bldtreedir = os.path.join(basedir, idir) # Avoid superfluous '/.' at the end of paths when d is '.' - if idir not in ('', '.'): - expdir = bldtreedir - else: - expdir = basedir + expdir = basedir if idir in {'', '.'} else bldtreedir srctreedir = os.path.join(build_to_src, expdir) res.append(f'{import_dir_arg}{srctreedir}') res.append(f'{import_dir_arg}{bldtreedir}') diff --git a/mesonbuild/compilers/detect.py b/mesonbuild/compilers/detect.py index c796c2f38aac..29c6ab42dd26 100644 --- a/mesonbuild/compilers/detect.py +++ b/mesonbuild/compilers/detect.py @@ -421,10 +421,7 @@ def sanitize(p: T.Optional[str]) -> T.Optional[str]: popen_exceptions[join_args(compiler + [arg])] = e version = search_version(out) match = re.search('^Target: (.*?)-', out, re.MULTILINE) - if match: - target = match.group(1) - else: - target = 'unknown target' + target = match.group(1) if match else 'unknown target' cls = c.ClangClCCompiler if lang == 'c' else cpp.ClangClCPPCompiler linker = guess_win_linker(env, ['lld-link'], cls, version, for_machine) return cls( diff --git a/mesonbuild/compilers/mixins/apple.py b/mesonbuild/compilers/mixins/apple.py index 98c4bfa1a18b..19e166c11c08 100644 --- a/mesonbuild/compilers/mixins/apple.py +++ b/mesonbuild/compilers/mixins/apple.py @@ -37,19 +37,13 @@ def openmp_flags(self, env: Environment) -> T.List[str]: """ m = env.machines[self.for_machine] assert m is not None, 'for mypy' - if m.cpu_family.startswith('x86'): - root = '/usr/local' - else: - root = '/opt/homebrew' + root = '/usr/local' if m.cpu_family.startswith('x86') else '/opt/homebrew' return self.__BASE_OMP_FLAGS + [f'-I{root}/opt/libomp/include'] def openmp_link_flags(self, env: Environment) -> T.List[str]: m = env.machines[self.for_machine] assert m is not None, 'for mypy' - if m.cpu_family.startswith('x86'): - root = '/usr/local' - else: - root = '/opt/homebrew' + root = '/usr/local' if m.cpu_family.startswith('x86') else '/opt/homebrew' link = self.find_library('omp', env, [f'{root}/opt/libomp/lib']) if not link: diff --git a/mesonbuild/compilers/mixins/clike.py b/mesonbuild/compilers/mixins/clike.py index 9f5fc505277d..7718188cff4a 100644 --- a/mesonbuild/compilers/mixins/clike.py +++ b/mesonbuild/compilers/mixins/clike.py @@ -66,10 +66,7 @@ def to_native(self, copy: bool = False) -> T.List[str]: # needed by static libraries that are provided by object files or # shared libraries. self.flush_pre_post() - if copy: - new = self.copy() - else: - new = self + new = self.copy() if copy else self # This covers all ld.bfd, ld.gold, ld.gold, and xild on Linux, which # all act like (or are) gnu ld # TODO: this could probably be added to the DynamicLinker instead @@ -1136,10 +1133,7 @@ def _find_library_real(self, libname: str, env: 'Environment', extra_dirs: T.Lis # detect, we will just skip path validity checks done in # get_library_dirs() call try: - if self.output_is_64bit(env): - elf_class = 2 - else: - elf_class = 1 + elf_class = 2 if self.output_is_64bit(env) else 1 except (mesonlib.MesonException, KeyError): # TODO evaluate if catching KeyError is wanted here elf_class = 0 # Search in the specified dirs, and then in the system libraries diff --git a/mesonbuild/compilers/mixins/emscripten.py b/mesonbuild/compilers/mixins/emscripten.py index 33b6134a344f..3fae5a410a88 100644 --- a/mesonbuild/compilers/mixins/emscripten.py +++ b/mesonbuild/compilers/mixins/emscripten.py @@ -43,10 +43,7 @@ def _get_compile_output(self, dirname: str, mode: CompileCheckMode) -> str: # Unlike sane toolchains, emcc infers the kind of output from its name. # This is the only reason why this method is overridden; compiler tests # do not work well with the default exe/obj suffices. - if mode == CompileCheckMode.LINK: - suffix = 'js' - else: - suffix = 'o' + suffix = 'js' if mode == CompileCheckMode.LINK else 'o' return os.path.join(dirname, 'output.' + suffix) def thread_link_flags(self, env: 'Environment') -> T.List[str]: @@ -78,9 +75,8 @@ def find_library(self, libname: str, env: 'Environment', extra_dirs: T.List[str] libtype: LibType = LibType.PREFER_SHARED, lib_prefix_warning: bool = True) -> T.Optional[T.List[str]]: if not libname.endswith('.js'): return super().find_library(libname, env, extra_dirs, libtype, lib_prefix_warning) - if os.path.isabs(libname): - if os.path.exists(libname): - return [libname] + if os.path.isabs(libname) and os.path.exists(libname): + return [libname] if len(extra_dirs) == 0: raise mesonlib.EnvironmentException('Looking up Emscripten JS libraries requires either an absolute path or specifying extra_dirs.') for d in extra_dirs: diff --git a/mesonbuild/compilers/mixins/visualstudio.py b/mesonbuild/compilers/mixins/visualstudio.py index 4ec22a0f28d0..9e010ffbcf57 100644 --- a/mesonbuild/compilers/mixins/visualstudio.py +++ b/mesonbuild/compilers/mixins/visualstudio.py @@ -238,16 +238,10 @@ def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]: i = name + '.lib' elif i.startswith('-isystem'): # just use /I for -isystem system include path s - if i.startswith('-isystem='): - i = '/I' + i[9:] - else: - i = '/I' + i[8:] + i = '/I' + i[9:] if i.startswith('-isystem=') else '/I' + i[8:] elif i.startswith('-idirafter'): # same as -isystem, but appends the path instead - if i.startswith('-idirafter='): - i = '/I' + i[11:] - else: - i = '/I' + i[10:] + i = '/I' + i[11:] if i.startswith('-idirafter=') else '/I' + i[10:] # -pthread in link flags is only used on Linux elif i == '-pthread': continue diff --git a/mesonbuild/compilers/vala.py b/mesonbuild/compilers/vala.py index f890ea81568f..8e14fe135b98 100644 --- a/mesonbuild/compilers/vala.py +++ b/mesonbuild/compilers/vala.py @@ -164,7 +164,7 @@ def build_wrapper_args(self, env: 'Environment', if a: p = a[0] n = p[max(p.rfind('/'), p.rfind('\\'))+1:] - if not n == d.get_name(): + if n != d.get_name(): args += ['--pkg=' + d.get_name()] # This is used by gio-2.0 among others. else: args += ['--pkg=' + n] diff --git a/mesonbuild/coredata.py b/mesonbuild/coredata.py index 83e83e728727..7419d8629566 100644 --- a/mesonbuild/coredata.py +++ b/mesonbuild/coredata.py @@ -745,10 +745,7 @@ def process_compiler_options(self, lang: str, comp: Compiler, env: Environment, enabled_opts: T.List[OptionKey] = [] for key in comp.base_options: - if subproject: - skey = key.evolve(subproject=subproject) - else: - skey = key + skey = key.evolve(subproject=subproject) if subproject else key if skey not in self.optstore: self.optstore.add_system_option(skey, copy.deepcopy(compilers.base_options[key])) if skey in env.options: @@ -882,7 +879,7 @@ def parse_cmd_line_options(args: SharedCMDOptions) -> None: # Merge builtin options set with --option into the dict. for key in chain( options.BUILTIN_OPTIONS.keys(), - (k.as_build() for k in options.BUILTIN_OPTIONS_PER_MACHINE.keys()), + (k.as_build() for k in options.BUILTIN_OPTIONS_PER_MACHINE), options.BUILTIN_OPTIONS_PER_MACHINE.keys(), ): name = str(key) diff --git a/mesonbuild/dependencies/cmake.py b/mesonbuild/dependencies/cmake.py index 5493e94ba79d..38e31f47bd39 100644 --- a/mesonbuild/dependencies/cmake.py +++ b/mesonbuild/dependencies/cmake.py @@ -336,11 +336,7 @@ def search_lib_dirs(path: str) -> bool: # Check the Linux CMake registry linux_reg = Path.home() / '.cmake' / 'packages' - for p in [linux_reg / name, linux_reg / lname]: - if p.exists(): - return True - - return False + return any(p.exists() for p in [linux_reg / name, linux_reg / lname]) def _detect_dep(self, name: str, package_version: str, modules: T.List[T.Tuple[str, bool]], components: T.List[T.Tuple[str, bool]], args: T.List[str]) -> None: # Detect a dependency with CMake using the '--find-package' mode diff --git a/mesonbuild/dependencies/detect.py b/mesonbuild/dependencies/detect.py index faf024de9c31..fa8863fccb7b 100644 --- a/mesonbuild/dependencies/detect.py +++ b/mesonbuild/dependencies/detect.py @@ -145,10 +145,7 @@ def find_external_dependency(name: str, env: 'Environment', kwargs: T.Dict[str, # otherwise, the dependency could not be found tried_methods = [d.log_tried() for d in pkgdep if d.log_tried()] - if tried_methods: - tried = mlog.format_list(tried_methods) - else: - tried = '' + tried = mlog.format_list(tried_methods) if tried_methods else '' mlog.log(type_text, mlog.bold(display_name), details + 'found:', mlog.red('NO'), f'(tried {tried})' if tried else '') diff --git a/mesonbuild/dependencies/factory.py b/mesonbuild/dependencies/factory.py index aac09cafa616..8167441d5dc9 100644 --- a/mesonbuild/dependencies/factory.py +++ b/mesonbuild/dependencies/factory.py @@ -110,10 +110,7 @@ def _process_method(method: DependencyMethods, env: 'Environment', for_machine: By default this only remove EXTRAFRAMEWORK dependencies for non-mac platforms. """ # Extra frameworks are only valid for macOS and other apple products - if (method is DependencyMethods.EXTRAFRAMEWORK and - not env.machines[for_machine].is_darwin()): - return False - return True + return not (method is DependencyMethods.EXTRAFRAMEWORK and not env.machines[for_machine].is_darwin()) def __call__(self, env: 'Environment', for_machine: MachineChoice, kwargs: T.Dict[str, T.Any]) -> T.List['DependencyGenerator']: diff --git a/mesonbuild/dependencies/misc.py b/mesonbuild/dependencies/misc.py index b5c40984a8e7..0f8f0f92b979 100644 --- a/mesonbuild/dependencies/misc.py +++ b/mesonbuild/dependencies/misc.py @@ -36,10 +36,7 @@ def netcdf_factory(env: 'Environment', candidates: T.List['DependencyGenerator'] = [] if DependencyMethods.PKGCONFIG in methods: - if language == 'fortran': - pkg = 'netcdf-fortran' - else: - pkg = 'netcdf' + pkg = 'netcdf-fortran' if language == 'fortran' else 'netcdf' candidates.append(functools.partial(PkgConfigDependency, pkg, env, kwargs, language=language)) diff --git a/mesonbuild/dependencies/python.py b/mesonbuild/dependencies/python.py index fff4aaa9e849..3b08de775636 100644 --- a/mesonbuild/dependencies/python.py +++ b/mesonbuild/dependencies/python.py @@ -174,10 +174,7 @@ def __init__(self, python_holder: 'BasicPythonExternalProgram', embed: bool): def find_libpy(self, environment: 'Environment') -> None: if self.is_pypy: - if self.major_version == 3: - libname = 'pypy3-c' - else: - libname = 'pypy-c' + libname = 'pypy3-c' if self.major_version == 3 else 'pypy-c' libdir = os.path.join(self.variables.get('base'), 'bin') libdirs = [libdir] else: diff --git a/mesonbuild/dependencies/qt.py b/mesonbuild/dependencies/qt.py index 1b60deb8afd2..63f61e5c2042 100644 --- a/mesonbuild/dependencies/qt.py +++ b/mesonbuild/dependencies/qt.py @@ -76,9 +76,8 @@ def _get_modules_lib_suffix(version: str, info: 'MachineInfo', is_debug: bool) - suffix += 'd' if version.startswith('4'): suffix += '4' - if info.is_darwin(): - if is_debug: - suffix += '_debug' + if info.is_darwin() and is_debug: + suffix += '_debug' if mesonlib.version_compare(version, '>= 5.14.0'): if info.is_android(): if info.cpu_family == 'x86': diff --git a/mesonbuild/dependencies/ui.py b/mesonbuild/dependencies/ui.py index cc17377a649b..07bc9f9722c1 100644 --- a/mesonbuild/dependencies/ui.py +++ b/mesonbuild/dependencies/ui.py @@ -102,7 +102,7 @@ def filter_args(args: T.List[str]) -> T.List[str]: or f.startswith('-f') \ or f.startswith('-I') \ or f == '-pthread' \ - or (f.startswith('-W') and not f == '-Wall'): + or (f.startswith('-W') and f != '-Wall'): result.append(f) return result diff --git a/mesonbuild/environment.py b/mesonbuild/environment.py index c26516215b6b..581299e3cbb6 100644 --- a/mesonbuild/environment.py +++ b/mesonbuild/environment.py @@ -106,10 +106,7 @@ def detect_lcov(lcov_exe: str = 'lcov', log: bool = False): def detect_llvm_cov(suffix: T.Optional[str] = None): # If there's a known suffix or forced lack of suffix, use that if suffix is not None: - if suffix == '': - tool = 'llvm-cov' - else: - tool = f'llvm-cov-{suffix}' + tool = 'llvm-cov' if suffix == '' else f'llvm-cov-{suffix}' if shutil.which(tool) is not None: return tool else: @@ -356,10 +353,7 @@ def detect_cpu_family(compilers: CompilersDict) -> str: elif trial in {'sun4u', 'sun4v'}: trial = 'sparc64' elif trial.startswith('mips'): - if '64' not in trial: - trial = 'mips' - else: - trial = 'mips64' + trial = 'mips64' if '64' in trial else 'mips' elif trial in {'ip30', 'ip35'}: trial = 'mips64' diff --git a/mesonbuild/interpreter/compiler.py b/mesonbuild/interpreter/compiler.py index 90514446bb12..3435e1facd39 100644 --- a/mesonbuild/interpreter/compiler.py +++ b/mesonbuild/interpreter/compiler.py @@ -546,10 +546,7 @@ def compiles_method(self, args: T.Tuple['mesonlib.FileOrString'], kwargs: 'Compi raise InterpreterException(f'Could not compile {testname}') if testname: - if result: - h = mlog.green('YES') - else: - h = mlog.red('NO') + h = mlog.green('YES') if result else mlog.red('NO') cached_msg = mlog.blue('(cached)') if cached else '' mlog.log('Checking if', mlog.bold(testname, True), msg, 'compiles:', h, cached_msg) return result @@ -596,10 +593,7 @@ def links_method(self, args: T.Tuple['mesonlib.FileOrString'], kwargs: 'CompileK raise InterpreterException(f'Could not link {testname if testname else "code"}') if testname: - if result: - h = mlog.green('YES') - else: - h = mlog.red('NO') + h = mlog.green('YES') if result else mlog.red('NO') cached_msg = mlog.blue('(cached)') if cached else '' mlog.log('Checking if', mlog.bold(testname, True), msg, 'links:', h, cached_msg) return result diff --git a/mesonbuild/interpreter/interpreter.py b/mesonbuild/interpreter/interpreter.py index 95d85ac07ebf..bc7d7b26c455 100644 --- a/mesonbuild/interpreter/interpreter.py +++ b/mesonbuild/interpreter/interpreter.py @@ -581,7 +581,7 @@ def check_stdlibs(self) -> None: machine_choices.append(MachineChoice.BUILD) for for_machine in machine_choices: props = self.build.environment.properties[for_machine] - for l in self.coredata.compilers[for_machine].keys(): + for l in self.coredata.compilers[for_machine]: try: di = mesonlib.stringlistify(props.get_stdlib(l)) except KeyError: @@ -745,13 +745,11 @@ def func_assert(self, node: mparser.FunctionNode, args: T.Tuple[bool, T.Optional raise InterpreterException('Assert failed: ' + message) def validate_arguments(self, args, argcount, arg_types): - if argcount is not None: - if argcount != len(args): - raise InvalidArguments(f'Expected {argcount} arguments, got {len(args)}.') + if argcount is not None and argcount != len(args): + raise InvalidArguments(f'Expected {argcount} arguments, got {len(args)}.') for actual, wanted in zip(args, arg_types): - if wanted is not None: - if not isinstance(actual, wanted): - raise InvalidArguments('Incorrect argument type.') + if wanted is not None and not isinstance(actual, wanted): + raise InvalidArguments('Incorrect argument type.') # Executables aren't actually accepted, but we allow them here to allow for # better error messages when overridden @@ -1126,7 +1124,7 @@ def set_backend(self) -> None: return from ..backend import backends - if OptionKey('genvslite') in self.user_defined_options.cmd_line_options.keys(): + if OptionKey('genvslite') in self.user_defined_options.cmd_line_options: # Use of the '--genvslite vsxxxx' option ultimately overrides any '--backend xxx' # option the user may specify. backend_name = self.coredata.get_option(OptionKey('genvslite')) @@ -3082,10 +3080,7 @@ def validate_installable_file(fpath: Path) -> bool: installabledirs = [str(Path(srcdir, s.source_subdir)) for s in self.build.install_dirs] if fpath in installablefiles: return True - for d in installabledirs: - if str(fpath).startswith(d): - return True - return False + return any(str(fpath).startswith(d) for d in installabledirs) norm = Path(fname) # variables built from a dep.get_variable are allowed to refer to @@ -3093,10 +3088,7 @@ def validate_installable_file(fpath: Path) -> bool: if validate_installable_file(norm): return norm = Path(os.path.abspath(Path(srcdir, subdir, fname))) - if os.path.isdir(norm): - inputtype = 'directory' - else: - inputtype = 'file' + inputtype = 'directory' if os.path.isdir(norm) else 'file' if InterpreterRuleRelaxation.ALLOW_BUILD_DIR_FILE_REFERENCES in self.relaxations and builddir in norm.parents: return if srcdir not in norm.parents: @@ -3465,7 +3457,7 @@ def kwarg_strings_to_includedirs(self, kwargs: kwtypes._BuildTarget) -> None: kwargs['d_import_dirs'] = cleaned_items def add_stdlib_info(self, target): - for l in target.compilers.keys(): + for l in target.compilers: dep = self.build.stdlibs[target.for_machine].get(l, None) if dep: target.add_deps(dep) diff --git a/mesonbuild/interpreter/type_checking.py b/mesonbuild/interpreter/type_checking.py index 0d92a3dbf7cc..8313b71c554e 100644 --- a/mesonbuild/interpreter/type_checking.py +++ b/mesonbuild/interpreter/type_checking.py @@ -75,7 +75,7 @@ def _install_mode_validator(mode: T.List[T.Union[str, bool, int]]) -> T.Optional return 'first component must be a permissions string or False' if isinstance(perms, str): - if not len(perms) == 9: + if len(perms) != 9: return ('permissions string must be exactly 9 characters in the form rwxr-xr-x,' f' got {len(perms)}') for i in [0, 3, 6]: diff --git a/mesonbuild/interpreterbase/decorators.py b/mesonbuild/interpreterbase/decorators.py index 6524aa92dd4f..4b58da011b36 100644 --- a/mesonbuild/interpreterbase/decorators.py +++ b/mesonbuild/interpreterbase/decorators.py @@ -290,9 +290,7 @@ def check(self, value: T.Any) -> bool: return False if self.pairs and len(value) % 2 != 0: return False - if not value and not self.allow_empty: - return False - return True + return not (not value and not self.allow_empty) def check_any(self, value: T.Any) -> bool: """Check a value should emit new/deprecated feature. @@ -506,7 +504,7 @@ def emit_feature_change(values: T.Dict[_T, T.Union[str, T.Tuple[str, str]]], fea if n in value: warning = f'value "{n}" in list' elif isinstance(value, dict): - if n in value.keys(): + if n in value: warning = f'value "{n}" in dict keys' elif n == value: warning = f'value "{n}"' diff --git a/mesonbuild/interpreterbase/disabler.py b/mesonbuild/interpreterbase/disabler.py index bad0d712977a..4b45f36d2d75 100644 --- a/mesonbuild/interpreterbase/disabler.py +++ b/mesonbuild/interpreterbase/disabler.py @@ -29,7 +29,4 @@ def is_disabled(args: T.Sequence[T.Any], kwargs: T.Dict[str, T.Any]) -> bool: for i in args: if _is_arg_disabled(i): return True - for i in kwargs.values(): - if _is_arg_disabled(i): - return True - return False + return any(_is_arg_disabled(i) for i in kwargs.values()) diff --git a/mesonbuild/linkers/detect.py b/mesonbuild/linkers/detect.py index cd3c7b2efd0f..740abe79e28b 100644 --- a/mesonbuild/linkers/detect.py +++ b/mesonbuild/linkers/detect.py @@ -89,10 +89,7 @@ def guess_win_linker(env: 'Environment', compiler: T.List[str], comp_class: T.Ty elif o.startswith('Microsoft') or e.startswith('Microsoft'): out = o or e match = re.search(r'.*(X86|X64|ARM|ARM64).*', out) - if match: - target = str(match.group(1)) - else: - target = 'x86' + target = str(match.group(1)) if match else 'x86' return linkers.MSVCDynamicLinker( for_machine, [], machine=target, exelist=compiler, diff --git a/mesonbuild/linkers/linkers.py b/mesonbuild/linkers/linkers.py index c3750ccc372f..1013995167e6 100644 --- a/mesonbuild/linkers/linkers.py +++ b/mesonbuild/linkers/linkers.py @@ -698,10 +698,7 @@ def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, paths = ':'.join(all_paths) if len(paths) < len(install_rpath): padding = 'X' * (len(install_rpath) - len(paths)) - if not paths: - paths = padding - else: - paths = paths + ':' + padding + paths = padding if not paths else paths + ':' + padding args.extend(self._apply_prefix('-rpath,' + paths)) # TODO: should this actually be "for solaris/sunos"? @@ -1451,10 +1448,7 @@ def build_rpath_args(self, env: 'Environment', build_dir: str, from_dir: str, paths = ':'.join(all_paths) if len(paths) < len(install_rpath): padding = 'X' * (len(install_rpath) - len(paths)) - if not paths: - paths = padding - else: - paths = paths + ':' + padding + paths = padding if not paths else paths + ':' + padding return (self._apply_prefix(f'-rpath,{paths}'), rpath_dirs_to_remove) def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str, diff --git a/mesonbuild/mcompile.py b/mesonbuild/mcompile.py index 2f5708c86521..c98d77a04896 100644 --- a/mesonbuild/mcompile.py +++ b/mesonbuild/mcompile.py @@ -115,10 +115,7 @@ def get_target_from_intro_data(target: ParsedTargetName, builddir: Path, introsp split = intro_target['id'].rsplit('@', 1) if len(split) > 1: split = split[0].split('@@', 1) - if len(split) > 1: - intro_target_name = split[1] - else: - intro_target_name = split[0] + intro_target_name = split[1] if len(split) > 1 else split[0] if ((target.type and target.type != intro_target['type'].replace(' ', '_')) or (target.name != intro_target_name) or (target.path and intro_target['filename'] != 'no_name' and @@ -135,10 +132,7 @@ def get_target_from_intro_data(target: ParsedTargetName, builddir: Path, introsp split = i['id'].rsplit('@', 1) if len(split) > 1: split = split[0].split('@@', 1) - if len(split) > 1: - i_name = split[1] - else: - i_name = split[0] + i_name = split[1] if len(split) > 1 else split[0] p = Path(i['filename'][0]).relative_to(resolved_bdir).parent / i_name t = i['type'].replace(' ', '_') suggestions.append(f'- ./{p}:{t}') diff --git a/mesonbuild/minstall.py b/mesonbuild/minstall.py index e5901c45ae85..b38b176835d2 100644 --- a/mesonbuild/minstall.py +++ b/mesonbuild/minstall.py @@ -371,9 +371,7 @@ def should_install(self, d: T.Union[TargetInstallData, InstallEmptyDir, ExecutableSerialisation]) -> bool: if d.subproject and (d.subproject in self.skip_subprojects or '*' in self.skip_subprojects): return False - if self.tags and d.tag not in self.tags: - return False - return True + return not (self.tags and d.tag not in self.tags) def log(self, msg: str) -> None: if not self.options.quiet: diff --git a/mesonbuild/modules/dlang.py b/mesonbuild/modules/dlang.py index 34fea9081f85..632c2506ad60 100644 --- a/mesonbuild/modules/dlang.py +++ b/mesonbuild/modules/dlang.py @@ -41,8 +41,7 @@ def _init_dub(self, state): self.dubbin = DlangModule.class_dubbin if not self.dubbin: - if not self.dubbin: - raise MesonException('DUB not found.') + raise MesonException('DUB not found.') @typed_pos_args('dlang.generate_dub_file', str, str) def generate_dub_file(self, state, args, kwargs): diff --git a/mesonbuild/modules/java.py b/mesonbuild/modules/java.py index abef4acdfffa..a5d07e3399dd 100644 --- a/mesonbuild/modules/java.py +++ b/mesonbuild/modules/java.py @@ -87,7 +87,7 @@ def __native_headers(self, state: ModuleState, args: T.Tuple[T.List[mesonlib.Fil '@INPUT@', ]) - prefix = classes[0] if not package else package + prefix = package or classes[0] target = CustomTarget(f'{prefix}-native-headers', state.subdir, diff --git a/mesonbuild/modules/pkgconfig.py b/mesonbuild/modules/pkgconfig.py index 16c8c079846d..b4b4d69f9a51 100644 --- a/mesonbuild/modules/pkgconfig.py +++ b/mesonbuild/modules/pkgconfig.py @@ -441,7 +441,7 @@ def _generate_pkgconfig_file(self, state: ModuleState, deps: DependenciesHelper, pkgroot: T.Optional[str] = None) -> None: coredata = state.environment.get_coredata() referenced_vars = set() - optnames = [x.name for x in BUILTIN_DIR_OPTIONS.keys()] + optnames = [x.name for x in BUILTIN_DIR_OPTIONS] if not dataonly: # includedir is always implied, although libdir may not be diff --git a/mesonbuild/msetup.py b/mesonbuild/msetup.py index 5dfda67056be..294c5abb0381 100644 --- a/mesonbuild/msetup.py +++ b/mesonbuild/msetup.py @@ -325,7 +325,7 @@ def run_genvslite_setup(options: CMDOptions) -> None: # The command line may specify a '--backend' option, which doesn't make sense in conjunction with # '--genvslite', where we always want to use a ninja back end - k_backend = OptionKey('backend') - if k_backend in options.cmd_line_options.keys(): + if k_backend in options.cmd_line_options: if options.cmd_line_options[k_backend] != 'ninja': raise MesonException('Explicitly specifying a backend option with \'genvslite\' is not necessary ' '(the ninja backend is always used) but specifying a non-ninja backend ' @@ -358,7 +358,7 @@ def run(options: T.Union[CMDOptions, T.List[str]]) -> int: # lie options.pager = False - if OptionKey('genvslite') in options.cmd_line_options.keys(): + if OptionKey('genvslite') in options.cmd_line_options: run_genvslite_setup(options) else: app = MesonApp(options) diff --git a/mesonbuild/optinterpreter.py b/mesonbuild/optinterpreter.py index a22152829b42..a6a59a6f8356 100644 --- a/mesonbuild/optinterpreter.py +++ b/mesonbuild/optinterpreter.py @@ -151,7 +151,7 @@ def reduce_arguments(self, args: mparser.ArgumentNode) -> T.Tuple['TYPE_var', 'T raise OptionException('All keyword arguments must be after positional arguments.') reduced_pos = [self.reduce_single(arg) for arg in args.arguments] reduced_kw = {} - for key in args.kwargs.keys(): + for key in args.kwargs: if not isinstance(key, mparser.IdNode): raise OptionException('Keyword argument name is not a string.') a = args.kwargs[key] diff --git a/mesonbuild/options.py b/mesonbuild/options.py index 912cfa23b978..b8ed696d34ce 100644 --- a/mesonbuild/options.py +++ b/mesonbuild/options.py @@ -779,9 +779,7 @@ def is_reserved_name(self, key: OptionKey) -> bool: # values. It is not, thank you very much. if prefix in ('b', 'backend'): # pylint: disable=R6201 return True - if prefix in self.all_languages: - return True - return False + return prefix in self.all_languages def is_builtin_option(self, key: OptionKey) -> bool: """Convenience method to check if this is a builtin option.""" @@ -802,9 +800,7 @@ def is_compiler_option(self, key: OptionKey) -> bool: if '_' not in key.name: return False prefix = key.name.split('_')[0] - if prefix in self.all_languages: - return True - return False + return prefix in self.all_languages def is_module_option(self, key: OptionKey) -> bool: return key in self.module_options diff --git a/mesonbuild/programs.py b/mesonbuild/programs.py index fbe241d99607..2189818fb3eb 100644 --- a/mesonbuild/programs.py +++ b/mesonbuild/programs.py @@ -153,9 +153,8 @@ def _windows_sanitize_path(path: str) -> str: @staticmethod def from_entry(name: str, command: T.Union[str, T.List[str]]) -> 'ExternalProgram': - if isinstance(command, list): - if len(command) == 1: - command = command[0] + if isinstance(command, list) and len(command) == 1: + command = command[0] # We cannot do any searching if the command is a list, and we don't # need to search if the path is an absolute path. if isinstance(command, list) or os.path.isabs(command): diff --git a/mesonbuild/rewriter.py b/mesonbuild/rewriter.py index 78517bf05f8b..2b93bdf57c21 100644 --- a/mesonbuild/rewriter.py +++ b/mesonbuild/rewriter.py @@ -233,10 +233,7 @@ def add_value(self, value): def _remove_helper(self, value, equal_func): def check_remove_node(node): - for j in value: - if equal_func(i, j): - return True - return False + return any(equal_func(i, j) for j in value) if not isinstance(value, list): value = [value] @@ -456,7 +453,7 @@ def process_default_options(self, cmd): 'id': "/", 'operation': 'remove_regex', 'kwargs': { - 'default_options': [f'{x}=.*' for x in cmd['options'].keys()] + 'default_options': [f'{x}=.*' for x in cmd['options']] } } self.process_kwargs(kwargs_cmd) @@ -647,10 +644,7 @@ def arg_list_from_node(n): if cmd['operation'] == 'src_add': node = None - if target['sources']: - node = target['sources'][0] - else: - node = target['node'] + node = target['sources'][0] if target['sources'] else target['node'] assert node is not None # Generate the current source list @@ -729,7 +723,7 @@ def find_node(src): # Specifying `extra_files` with a list that flattens to empty gives an empty # target['extra_files'] list, account for that. try: - extra_files_key = next(k for k in tgt_function.args.kwargs.keys() if isinstance(k, IdNode) and k.value == 'extra_files') + extra_files_key = next(k for k in tgt_function.args.kwargs if isinstance(k, IdNode) and k.value == 'extra_files') node = tgt_function.args.kwargs[extra_files_key] except StopIteration: # Target has no extra_files kwarg, create one diff --git a/mesonbuild/scripts/coverage.py b/mesonbuild/scripts/coverage.py index f01946944afe..2ce381e09286 100644 --- a/mesonbuild/scripts/coverage.py +++ b/mesonbuild/scripts/coverage.py @@ -28,10 +28,7 @@ def coverage(outputs: T.List[str], source_root: str, subproject_root: str, build # so don't exclude subprojects ourselves, if the project has a config, # because they either don't want that, or should set it themselves lcovrc = os.path.join(source_root, '.lcovrc') - if os.path.exists(lcovrc): - lcov_config = ['--config-file', lcovrc] - else: - lcov_config = [] + lcov_config = ['--config-file', lcovrc] if os.path.exists(lcovrc) else [] if lcov_exe and mesonlib.version_compare(lcov_version, '>=2.0'): lcov_exe_rc_branch_coverage = ['--rc', 'branch_coverage=1'] diff --git a/mesonbuild/scripts/depfixer.py b/mesonbuild/scripts/depfixer.py index db9c97d98c6a..6b794652bb2b 100644 --- a/mesonbuild/scripts/depfixer.py +++ b/mesonbuild/scripts/depfixer.py @@ -27,10 +27,7 @@ class DataSizes: def __init__(self, ptrsize: int, is_le: bool) -> None: - if is_le: - p = '<' - else: - p = '>' + p = '<' if is_le else '>' self.Half = p + 'h' self.HalfSize = 2 self.Word = p + 'I' @@ -328,9 +325,8 @@ def fix_rpathtype_entry(self, fname: str, rpath_dirs_to_remove: T.Set[bytes], ne # specified by user with build_rpath. for rpath_dir in old_rpath.split(b':'): if not (rpath_dir in rpath_dirs_to_remove or - rpath_dir == (b'X' * len(rpath_dir))): - if rpath_dir: - new_rpaths.add(rpath_dir) + rpath_dir == (b'X' * len(rpath_dir))) and rpath_dir: + new_rpaths.add(rpath_dir) # Prepend user-specified new entries while preserving the ones that came from pkgconfig etc. new_rpath = b':'.join(new_rpaths) diff --git a/mesonbuild/scripts/depscan.py b/mesonbuild/scripts/depscan.py index 44e805447713..42a22562eb92 100644 --- a/mesonbuild/scripts/depscan.py +++ b/mesonbuild/scripts/depscan.py @@ -113,10 +113,7 @@ def module_name_for(self, src: str, lang: Literal['cpp', 'fortran']) -> str: # Module foo:bar goes to a file name foo@bar.smod # Module Foo goes to a file name foo.mod namebase = exported.replace(':', '@') - if ':' in exported: - extension = 'smod' - else: - extension = 'mod' + extension = 'smod' if ':' in exported else 'mod' return os.path.join(self.target_data.private_dir, f'{namebase}.{extension}') return '{}.ifc'.format(self.exports[src]) diff --git a/mesonbuild/scripts/externalproject.py b/mesonbuild/scripts/externalproject.py index ce49fbcbf26e..95b954bc8939 100644 --- a/mesonbuild/scripts/externalproject.py +++ b/mesonbuild/scripts/externalproject.py @@ -41,9 +41,7 @@ def write_stampfile(self) -> None: def supports_jobs_flag(self) -> bool: p, o, e = Popen_safe(self.make + ['--version']) - if p.returncode == 0 and ('GNU Make' in o or 'waf' in o): - return True - return False + return bool(p.returncode == 0 and ('GNU Make' in o or 'waf' in o)) def build(self) -> int: make_cmd = self.make.copy() diff --git a/mesonbuild/scripts/gtkdochelper.py b/mesonbuild/scripts/gtkdochelper.py index 06844289fc1a..50b797a6381b 100644 --- a/mesonbuild/scripts/gtkdochelper.py +++ b/mesonbuild/scripts/gtkdochelper.py @@ -160,10 +160,7 @@ def build_gtkdoc(source_root: str, build_root: str, doc_subdir: str, src_subdirs if mode == 'auto': # Guessing is probably a poor idea but these keeps compat # with previous behavior - if main_file.endswith('sgml'): - modeflag = '--sgml-mode' - else: - modeflag = '--xml-mode' + modeflag = '--sgml-mode' if main_file.endswith('sgml') else '--xml-mode' elif mode == 'xml': modeflag = '--xml-mode' elif mode == 'sgml': @@ -217,26 +214,11 @@ def install_gtkdoc(build_root: str, doc_subdir: str, install_prefix: str, datadi def run(args: T.List[str]) -> int: options = parser.parse_args(args) - if options.htmlargs: - htmlargs = options.htmlargs.split('@@') - else: - htmlargs = [] - if options.scanargs: - scanargs = options.scanargs.split('@@') - else: - scanargs = [] - if options.scanobjsargs: - scanobjsargs = options.scanobjsargs.split('@@') - else: - scanobjsargs = [] - if options.fixxrefargs: - fixxrefargs = options.fixxrefargs.split('@@') - else: - fixxrefargs = [] - if options.mkdbargs: - mkdbargs = options.mkdbargs.split('@@') - else: - mkdbargs = [] + htmlargs = options.htmlargs.split('@@') if options.htmlargs else [] + scanargs = options.scanargs.split('@@') if options.scanargs else [] + scanobjsargs = options.scanobjsargs.split('@@') if options.scanobjsargs else [] + fixxrefargs = options.fixxrefargs.split('@@') if options.fixxrefargs else [] + mkdbargs = options.mkdbargs.split('@@') if options.mkdbargs else [] build_gtkdoc( options.sourcedir, options.builddir, diff --git a/mesonbuild/utils/universal.py b/mesonbuild/utils/universal.py index 574bcb51f654..18d7ac88e2b8 100644 --- a/mesonbuild/utils/universal.py +++ b/mesonbuild/utils/universal.py @@ -1083,10 +1083,7 @@ def default_sysconfdir() -> str: def has_path_sep(name: str, sep: str = '/\\') -> bool: 'Checks if any of the specified @sep path separators are in @name' - for each in sep: - if each in name: - return True - return False + return any(each in name for each in sep) if is_windows(): @@ -1876,10 +1873,7 @@ def detect_subprojects(spdir_name: str, current_dir: str = '', def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool: - for s in strlist: - if substr in s: - return True - return False + return any(substr in s for s in strlist) class OrderedSet(T.MutableSet[_T]): @@ -1904,7 +1898,7 @@ def __repr__(self) -> str: # Don't print 'OrderedSet("")' for an empty set. if self.__container: return 'OrderedSet([{}])'.format( - ', '.join(repr(e) for e in self.__container.keys())) + ', '.join(repr(e) for e in self.__container)) return 'OrderedSet()' def __reversed__(self) -> T.Iterator[_T]: diff --git a/mesonbuild/wrap/wrap.py b/mesonbuild/wrap/wrap.py index 3fe40ed9f322..329199244c39 100644 --- a/mesonbuild/wrap/wrap.py +++ b/mesonbuild/wrap/wrap.py @@ -354,7 +354,7 @@ def load_wraps(self) -> None: self.add_wrap(wrap) def add_wrap(self, wrap: PackageDefinition) -> None: - for k in wrap.provided_deps.keys(): + for k in wrap.provided_deps: if k in self.provided_deps: prev_wrap = self.provided_deps[k] m = f'Multiple wrap files provide {k!r} dependency: {wrap.name} and {prev_wrap.name}' diff --git a/mesonbuild/wrap/wraptool.py b/mesonbuild/wrap/wraptool.py index 5486a26a7782..636baa537228 100644 --- a/mesonbuild/wrap/wraptool.py +++ b/mesonbuild/wrap/wraptool.py @@ -66,7 +66,7 @@ def add_arguments(parser: 'argparse.ArgumentParser') -> None: def list_projects(options: 'argparse.Namespace') -> None: releases = get_releases(options.allow_insecure) - for p in releases.keys(): + for p in releases: print(p) def search(options: 'argparse.Namespace') -> None: diff --git a/run_project_tests.py b/run_project_tests.py index fe1f46f7eefa..a825b6d86b48 100755 --- a/run_project_tests.py +++ b/run_project_tests.py @@ -496,10 +496,7 @@ def _compare_output(expected: T.List[T.Dict[str, str]], output: str, desc: str) # (There should probably be a way to turn this off for more complex # cases which don't fit this) if mesonlib.is_windows(): - if how != "re": - sub = r'\\' - else: - sub = r'\\\\' + sub = '\\\\' if how != 're' else '\\\\\\\\' expected_line = re.sub(r'/(?=.*(WARNING|ERROR|DEPRECATION))', sub, expected_line) m = OutputMatch(how, expected_line, count) @@ -967,9 +964,7 @@ def have_d_compiler() -> bool: # Don't know why. Don't know how to fix. Skip in this case. cp = subprocess.run(['dmd', '--version'], capture_output=True) - if cp.stdout == b'': - return False - return True + return cp.stdout != b'' return False def have_objc_compiler(use_tmp: bool) -> bool: @@ -998,9 +993,7 @@ def have_working_compiler(lang: str, use_tmp: bool) -> bool: return True def have_java() -> bool: - if shutil.which('javac') and shutil.which('java'): - return True - return False + return bool(shutil.which('javac') and shutil.which('java')) def skip_dont_care(t: TestDef) -> bool: # Everything is optional when not running on CI @@ -1011,10 +1004,7 @@ def skip_dont_care(t: TestDef) -> bool: if not t.category.endswith('frameworks'): return True - if mesonlib.is_osx() and '6 gettext' in str(t.path): - return True - - return False + return bool(mesonlib.is_osx() and '6 gettext' in str(t.path)) def skip_csharp(backend: Backend) -> bool: if backend is not Backend.ninja: @@ -1060,17 +1050,12 @@ def should_skip_rust(backend: Backend) -> bool: return True if backend is not Backend.ninja: return True - if mesonlib.is_windows(): - if has_broken_rustc(): - return True - return False + return bool(mesonlib.is_windows() and has_broken_rustc()) def should_skip_wayland() -> bool: if mesonlib.is_windows() or mesonlib.is_osx(): return True - if not shutil.which('wayland-scanner'): - return True - return False + return bool(not shutil.which('wayland-scanner')) def detect_tests_to_run(only: T.Dict[str, T.List[str]], use_tmp: bool) -> T.List[T.Tuple[str, T.List[TestDef], bool]]: """ @@ -1142,9 +1127,9 @@ def __init__(self, category: str, subdir: str, skip: bool = False, stdout_mandat assert categories == ALL_TESTS, 'argparse("--only", choices=ALL_TESTS) need to be updated to match all_tests categories' if only: - for key in only.keys(): + for key in only: assert key in categories, f'key `{key}` is not a recognized category' - all_tests = [t for t in all_tests if t.category in only.keys()] + all_tests = [t for t in all_tests if t.category in only] gathered_tests = [(t.category, gather_tests(Path('test cases', t.subdir), t.stdout_mandatory, only[t.category], t.skip), t.skip) for t in all_tests] return gathered_tests diff --git a/run_tests.py b/run_tests.py index 4e22028b830c..e2ca82ec5467 100755 --- a/run_tests.py +++ b/run_tests.py @@ -178,10 +178,7 @@ def get_convincing_fake_env_and_cc(bdir, prefix): else: meson_exe = None -if mesonlib.is_windows() or mesonlib.is_cygwin(): - exe_suffix = '.exe' -else: - exe_suffix = '' +exe_suffix = '.exe' if mesonlib.is_windows() or mesonlib.is_cygwin() else '' def handle_meson_skip_test(out: str) -> T.Tuple[bool, str]: for line in out.splitlines(): diff --git a/test cases/common/14 configure file/check_file.py b/test cases/common/14 configure file/check_file.py index 7d96b2aec7aa..e4c1266c02cd 100644 --- a/test cases/common/14 configure file/check_file.py +++ b/test cases/common/14 configure file/check_file.py @@ -9,9 +9,7 @@ def permit_osx_workaround(m1, m2): return False if m2 % 10000 != 0: return False - if m1//10000 != m2//10000: - return False - return True + return m1 // 10000 == m2 // 10000 if len(sys.argv) == 2: assert os.path.exists(sys.argv[1]) diff --git a/test cases/common/179 escape and unicode/find.py b/test cases/common/179 escape and unicode/find.py index 34a3eb835e83..06f14e59c6ea 100644 --- a/test cases/common/179 escape and unicode/find.py +++ b/test cases/common/179 escape and unicode/find.py @@ -4,6 +4,5 @@ import sys for fh in os.listdir('.'): - if os.path.isfile(fh): - if fh.endswith('.c'): - sys.stdout.write(fh + '\0') + if os.path.isfile(fh) and fh.endswith('.c'): + sys.stdout.write(fh + '\0') diff --git a/test cases/common/50 custom target chain/usetarget/subcomp.py b/test cases/common/50 custom target chain/usetarget/subcomp.py index 52dc0bbb5d1e..77c2cbcd6528 100755 --- a/test cases/common/50 custom target chain/usetarget/subcomp.py +++ b/test cases/common/50 custom target chain/usetarget/subcomp.py @@ -2,6 +2,5 @@ import sys -with open(sys.argv[1], 'rb') as ifile: - with open(sys.argv[2], 'w') as ofile: - ofile.write('Everything ok.\n') +with open(sys.argv[1], 'rb') as ifile, open(sys.argv[2], 'w') as ofile: + ofile.write('Everything ok.\n') diff --git a/test cases/common/95 manygen/subdir/manygen.py b/test cases/common/95 manygen/subdir/manygen.py index 931fb61de557..069d8a4ea960 100755 --- a/test cases/common/95 manygen/subdir/manygen.py +++ b/test cases/common/95 manygen/subdir/manygen.py @@ -21,10 +21,7 @@ if compiler_type == 'msvc': libsuffix = '.lib' is_vs = True - if any(['clang-cl' in c for c in compiler]): - linker = 'llvm-lib' - else: - linker = 'lib' + linker = 'llvm-lib' if any(['clang-cl' in c for c in compiler]) else 'lib' else: libsuffix = '.a' is_vs = False diff --git a/test cases/failing/89 custom target install data/preproc.py b/test cases/failing/89 custom target install data/preproc.py index e6eba4c6ac2a..4c13c576e43a 100644 --- a/test cases/failing/89 custom target install data/preproc.py +++ b/test cases/failing/89 custom target install data/preproc.py @@ -8,6 +8,5 @@ inf = sys.argv[1] outf = sys.argv[2] -with open(outf, 'wb') as o: - with open(inf, 'rb') as i: - o.write(i.read()) +with open(outf, 'wb') as o, open(inf, 'rb') as i: + o.write(i.read()) diff --git a/test cases/unit/60 identity cross/build_wrapper.py b/test cases/unit/60 identity cross/build_wrapper.py index 15d5c07dde5a..95eab32cb2ba 100755 --- a/test cases/unit/60 identity cross/build_wrapper.py +++ b/test cases/unit/60 identity cross/build_wrapper.py @@ -3,9 +3,6 @@ import subprocess, sys, platform # Meson does not yet support Studio cc on Solaris, only gcc or clang -if platform.system() == 'SunOS': - cc = 'gcc' -else: - cc = 'cc' +cc = 'gcc' if platform.system() == 'SunOS' else 'cc' subprocess.call([cc, "-DEXTERNAL_BUILD"] + sys.argv[1:]) diff --git a/test cases/unit/60 identity cross/host_wrapper.py b/test cases/unit/60 identity cross/host_wrapper.py index a3a694a4c113..8be747615588 100755 --- a/test cases/unit/60 identity cross/host_wrapper.py +++ b/test cases/unit/60 identity cross/host_wrapper.py @@ -3,9 +3,6 @@ import subprocess, sys, platform # Meson does not yet support Studio cc on Solaris, only gcc or clang -if platform.system() == 'SunOS': - cc = 'gcc' -else: - cc = 'cc' +cc = 'gcc' if platform.system() == 'SunOS' else 'cc' subprocess.call([cc, "-DEXTERNAL_HOST"] + sys.argv[1:]) diff --git a/tools/cmake2meson.py b/tools/cmake2meson.py index f9153d109da1..74d2143717bf 100755 --- a/tools/cmake2meson.py +++ b/tools/cmake2meson.py @@ -210,10 +210,7 @@ def write_entry(self, outfile: T.TextIO, t: Statement) -> None: elif t.name == 'option': optname = t.args[0].value description = t.args[1].value - if len(t.args) > 2: - default = t.args[2].value - else: - default = None + default = t.args[2].value if len(t.args) > 2 else None self.options.append((optname, description, default)) return elif t.name == 'project': diff --git a/tools/regenerate_docs.py b/tools/regenerate_docs.py index b7484e7657dc..41c2c2fba0c2 100755 --- a/tools/regenerate_docs.py +++ b/tools/regenerate_docs.py @@ -117,7 +117,7 @@ def generate_hotdoc_includes(root_dir: Path, output_dir: Path) -> None: cmd_data = get_commands_data(root_dir) for cmd, parsed in cmd_data.items(): - for typ in parsed.keys(): + for typ in parsed: with open(output_dir / (cmd+'_'+typ+'.inc'), 'w', encoding='utf-8') as f: f.write(parsed[typ]) diff --git a/unittests/allplatformstests.py b/unittests/allplatformstests.py index 40085983710a..303dfd52a397 100644 --- a/unittests/allplatformstests.py +++ b/unittests/allplatformstests.py @@ -1190,10 +1190,7 @@ def test_always_prefer_c_compiler_for_asm(self): for cmd in self.get_compdb(): # Get compiler split = split_args(cmd['command']) - if split[0] in ('ccache', 'sccache'): - compiler = split[1] - else: - compiler = split[0] + compiler = split[1] if split[0] in {'ccache', 'sccache'} else split[0] # Classify commands if 'Ic-asm' in cmd['command']: if cmd['file'].endswith('.S'): @@ -1362,9 +1359,8 @@ def test_lto_threads(self): env = get_fake_env(testdir, self.builddir, self.prefix) cc = detect_c_compiler(env, MachineChoice.HOST) extra_args: T.List[str] = [] - if cc.get_id() == 'clang': - if is_windows(): - raise SkipTest('LTO not (yet) supported by windows clang') + if cc.get_id() == 'clang' and is_windows(): + raise SkipTest('LTO not (yet) supported by windows clang') self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_threads=8'] + extra_args) self.build() @@ -1426,11 +1422,7 @@ def has_working_hg(self): # This check should not be necessary, but # CI under macOS passes the above test even # though Mercurial is not installed. - if subprocess.call(['hg', '--version'], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL) != 0: - return False - return True + return subprocess.call(['hg', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0 except FileNotFoundError: return False @@ -3241,7 +3233,7 @@ def assertKeyTypes(key_type_list, obj, strict: bool = True): self.assertIn(i[0], obj) self.assertIsInstance(obj[i[0]], i[1]) if strict: - for k in obj.keys(): + for k in obj: found = False for i in key_type_list: if k == i[0]: diff --git a/unittests/baseplatformtests.py b/unittests/baseplatformtests.py index 6e6a01d40fd3..7e09617254af 100644 --- a/unittests/baseplatformtests.py +++ b/unittests/baseplatformtests.py @@ -291,10 +291,7 @@ def run_target(self, target, *, override_envvars=None): return self.build(target=target, override_envvars=override_envvars) def setconf(self, arg: T.Sequence[str], will_build: bool = True) -> None: - if isinstance(arg, str): - arg = [arg] - else: - arg = list(arg) + arg = [arg] if isinstance(arg, str) else list(arg) self._run(self.mconf_command + arg + [self.builddir]) def getconf(self, optname: str): diff --git a/unittests/helpers.py b/unittests/helpers.py index 5e919295515d..1797d51ebcf4 100644 --- a/unittests/helpers.py +++ b/unittests/helpers.py @@ -198,9 +198,8 @@ def get_rpath(fname: str) -> T.Optional[str]: def get_classpath(fname: str) -> T.Optional[str]: - with zipfile.ZipFile(fname) as zip: - with zip.open('META-INF/MANIFEST.MF') as member: - contents = member.read().decode().strip() + with zipfile.ZipFile(fname) as zip, zip.open('META-INF/MANIFEST.MF') as member: + contents = member.read().decode().strip() lines: T.List[str] = [] for line in contents.splitlines(): if line.startswith(' '): diff --git a/unittests/internaltests.py b/unittests/internaltests.py index fa0e440d3583..ee7b4e092bb1 100644 --- a/unittests/internaltests.py +++ b/unittests/internaltests.py @@ -990,24 +990,23 @@ def test_sort_libpaths(self): def test_dependency_factory_order(self): b = mesonbuild.dependencies.base F = mesonbuild.dependencies.factory - with tempfile.TemporaryDirectory() as tmpdir: - with chdir(tmpdir): - env = get_fake_env() - env.scratch_dir = tmpdir - - f = F.DependencyFactory( - 'test_dep', - methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE] - ) - actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] - self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake']) - - f = F.DependencyFactory( - 'test_dep', - methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG] - ) - actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] - self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig']) + with tempfile.TemporaryDirectory() as tmpdir, chdir(tmpdir): + env = get_fake_env() + env.scratch_dir = tmpdir + + f = F.DependencyFactory( + 'test_dep', + methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE] + ) + actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] + self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake']) + + f = F.DependencyFactory( + 'test_dep', + methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG] + ) + actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] + self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig']) def test_validate_json(self) -> None: """Validate the json schema for the test cases.""" @@ -1026,10 +1025,7 @@ def test_validate_json(self) -> None: with open('data/test.schema.json', 'r', encoding='utf-8') as f: data = json.loads(f.read()) - if fast: - schema_validator = compile(data) - else: - schema_validator = lambda x: validate(x, schema=data) + schema_validator = compile(data) if fast else lambda x: validate(x, schema=data) errors: T.List[T.Tuple[Path, Exception]] = [] for p in Path('test cases').glob('**/test.json'): diff --git a/unittests/linuxliketests.py b/unittests/linuxliketests.py index 16997e393339..98d0bb08698e 100644 --- a/unittests/linuxliketests.py +++ b/unittests/linuxliketests.py @@ -1352,7 +1352,7 @@ def test_link_arg_fullname(self): # before v0.28, Libs flags like -Wl will not kept in context order with -l flags. # see https://gitlab.freedesktop.org/pkg-config/pkg-config/-/blob/master/NEWS pkgconfigver = subprocess.check_output([PKG_CONFIG, '--version']) - if b'0.28' > pkgconfigver: + if pkgconfigver < b'0.28': raise SkipTest('pkg-config is too old to be correctly done this.') self.run_tests() @@ -1604,10 +1604,7 @@ def test_ld_environment_variable_fortran(self): def test_ld_environment_variable_d(self): # At least for me, ldc defaults to gold, and gdc defaults to bfd, so # let's pick lld, which isn't the default for either (currently) - if is_osx(): - expected = 'ld64' - else: - expected = 'ld.lld' + expected = 'ld64' if is_osx() else 'ld.lld' self._check_ld('ld.lld', 'lld', 'd', expected) def compute_sha256(self, filename): diff --git a/unittests/machinefiletests.py b/unittests/machinefiletests.py index 5ff862cdcfb1..741bf4a9646d 100644 --- a/unittests/machinefiletests.py +++ b/unittests/machinefiletests.py @@ -94,10 +94,7 @@ def helper_create_binary_wrapper(self, binary, dir_=None, extra_args=None, **kwa filename = os.path.join(dir_ or self.builddir, f'binary_wrapper{self.current_wrapper}.py') extra_args = extra_args or {} self.current_wrapper += 1 - if is_haiku(): - chbang = '#!/bin/env python3' - else: - chbang = '#!/usr/bin/env python3' + chbang = '#!/bin/env python3' if is_haiku() else '#!/usr/bin/env python3' with open(filename, 'wt', encoding='utf-8') as f: f.write(textwrap.dedent('''\ diff --git a/unittests/pythontests.py b/unittests/pythontests.py index aaea906ea829..c4f243f8c2f7 100644 --- a/unittests/pythontests.py +++ b/unittests/pythontests.py @@ -72,7 +72,7 @@ def _test_bytecompile(self, py2=False): self.assertLength(cached, 2) count += 1 # there are 5 files x 2 installations - if py2 and not cc.get_id() == 'msvc': + if py2 and cc.get_id() != 'msvc': self.assertEqual(count, 10) else: self.assertEqual(count, 5) diff --git a/unittests/subprojectscommandtests.py b/unittests/subprojectscommandtests.py index 85950a08450b..51f98ce77399 100644 --- a/unittests/subprojectscommandtests.py +++ b/unittests/subprojectscommandtests.py @@ -95,10 +95,7 @@ def _git_create_remote_tag(self, name, tag): def _wrap_create_git(self, name, revision='master', depth=None): path = self.root_dir / name with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w', encoding='utf-8') as f: - if depth is None: - depth_line = '' - else: - depth_line = 'depth = {}'.format(depth) + depth_line = '' if depth is None else 'depth = {}'.format(depth) f.write(textwrap.dedent( ''' [wrap-git]