misc,python: Run pre-commit run --all-files

Applies the `pyupgrade` hook to all files in the repo.

Change-Id: I9879c634a65c5fcaa9567c63bc5977ff97d5d3bf
This commit is contained in:
Bobby R. Bruce
2023-10-09 13:40:03 -07:00
parent 83af4525ce
commit 298119e402
188 changed files with 741 additions and 779 deletions

View File

@@ -91,7 +91,7 @@ class LupvBoard(AbstractSystemBoard, KernelDiskWorkload):
cache_hierarchy: AbstractCacheHierarchy,
) -> None:
if cache_hierarchy.is_ruby():
raise EnvironmentError("RiscvBoard is not compatible with Ruby")
raise OSError("RiscvBoard is not compatible with Ruby")
if processor.get_isa() != ISA.RISCV:
raise Exception(

View File

@@ -66,7 +66,7 @@ class AbstractNode(Cache_Controller):
# TODO: I don't love that we have to pass in the cache line size.
# However, we need some way to set the index bits
def __init__(self, network: RubyNetwork, cache_line_size: int):
super(AbstractNode, self).__init__()
super().__init__()
# Note: Need to call versionCount method on *this* class, not the
# potentially derived class

View File

@@ -54,7 +54,7 @@ class AbstractProcessor(SubSystem):
if cores:
# In the stdlib we assume the system processor conforms to a single
# ISA target.
assert len(set(core.get_isa() for core in cores)) == 1
assert len({core.get_isa() for core in cores}) == 1
self.cores = cores
self._isa = cores[0].get_isa()
else:

View File

@@ -62,7 +62,7 @@ def get_cpu_type_from_str(input: str) -> CPUTypes:
if input.lower() == cpu_type.value:
return cpu_type
valid_cpu_types_list_str = str()
valid_cpu_types_list_str = ""
for cpu_type_str in get_cpu_types_str_set():
valid_cpu_types_list_str += f"{os.linesep}{cpu_type_str}"

View File

@@ -63,7 +63,7 @@ class SwitchableProcessor(AbstractProcessor):
# In the stdlib we assume the system processor conforms to a single
# ISA target.
assert len(set(core.get_isa() for core in self._current_cores)) == 1
assert len({core.get_isa() for core in self._current_cores}) == 1
super().__init__(isa=self._current_cores[0].get_isa())
for name, core_list in self._switchable_cores.items():
@@ -113,8 +113,7 @@ class SwitchableProcessor(AbstractProcessor):
def _all_cores(self):
for core_list in self._switchable_cores.values():
for core in core_list:
yield core
yield from core_list
def switch_to_processor(self, switchable_core_key: str):
# Run various checks.

View File

@@ -80,7 +80,7 @@ def get_isa_from_str(input: str) -> ISA:
if input.lower() == isa.value:
return isa
valid_isas_str_list = str()
valid_isas_str_list = ""
for isa_str in get_isas_str_set():
valid_isas_str_list += f"{os.linesep}{isa_str}"

View File

@@ -41,7 +41,7 @@ def getFileContent(file_path: Path) -> Dict:
:return: The content of the file
"""
if file_path.exists():
with open(file_path, "r") as file:
with open(file_path) as file:
return json.load(file)
else:
raise Exception(f"File not found at {file_path}")

View File

@@ -686,8 +686,7 @@ class SuiteResource(AbstractResource):
:yields: A generator that iterates over the workloads in the suite.
"""
for workload in self._workloads.keys():
yield workload
yield from self._workloads.keys()
def __len__(self):
"""

View File

@@ -48,8 +48,7 @@ def warn_default_decorator(gen: Generator, type: str, effect: str):
f"No behavior was set by the user for {type}."
f" Default behavior is {effect}."
)
for value in gen(*args, **kw_args):
yield value
yield from gen(*args, **kw_args)
return wrapped_generator

View File

@@ -32,7 +32,7 @@ class FileLockException(Exception):
pass
class FileLock(object):
class FileLock:
"""A file locking mechanism that has context-manager support so
you can use it in a with statement. This should be relatively cross
compatible as it doesn't rely on msvcrt or fcntl for the locking.

View File

@@ -42,7 +42,7 @@ class ByteCodeLoader(importlib.abc.Loader):
# Simple importer that allows python to import data from a dict of
# code objects. The keys are the module path, and the items are the
# filename and bytecode of the file.
class CodeImporter(object):
class CodeImporter:
def __init__(self):
self.modules = {}
override_var = os.environ.get("M5_OVERRIDE_PY_SOURCE", "false")
@@ -61,7 +61,7 @@ class CodeImporter(object):
abspath, code = self.modules[fullname]
if self.override and os.path.exists(abspath):
src = open(abspath, "r").read()
src = open(abspath).read()
code = compile(src, abspath, "exec")
is_package = os.path.basename(abspath) == "__init__.py"

View File

@@ -521,7 +521,7 @@ def cxxMethod(*args, **kwargs):
# This class holds information about each simobject parameter
# that should be displayed on the command line for use in the
# configuration system.
class ParamInfo(object):
class ParamInfo:
def __init__(self, type, desc, type_str, example, default_val, access_str):
self.type = type
self.desc = desc
@@ -546,7 +546,7 @@ class SimObjectCliWrapperException(Exception):
super().__init__(message)
class SimObjectCliWrapper(object):
class SimObjectCliWrapper:
"""
Wrapper class to restrict operations that may be done
from the command line on SimObjects.
@@ -609,7 +609,7 @@ class SimObjectCliWrapper(object):
# The SimObject class is the root of the special hierarchy. Most of
# the code in this class deals with the configuration hierarchy itself
# (parent/child node relationships).
class SimObject(object, metaclass=MetaSimObject):
class SimObject(metaclass=MetaSimObject):
# Specify metaclass. Any class inheriting from SimObject will
# get this metaclass.
type = "SimObject"
@@ -874,7 +874,7 @@ class SimObject(object, metaclass=MetaSimObject):
hr_value = value
value = param.convert(value)
except Exception as e:
msg = "%s\nError setting param %s.%s to %s\n" % (
msg = "{}\nError setting param {}.{} to {}\n".format(
e,
self.__class__.__name__,
attr,
@@ -1253,8 +1253,7 @@ class SimObject(object, metaclass=MetaSimObject):
# it based on the key (name) to ensure the order is the same
# on all hosts
for name, child in sorted(self._children.items()):
for obj in child.descendants():
yield obj
yield from child.descendants()
# Call C++ to create C++ object corresponding to this object
def createCCObject(self):
@@ -1287,8 +1286,7 @@ class SimObject(object, metaclass=MetaSimObject):
def recurseDeviceTree(self, state):
for child in self._children.values():
for item in child: # For looping over SimObjectVectors
for dt in item.generateDeviceTree(state):
yield dt
yield from item.generateDeviceTree(state)
# On a separate method otherwise certain buggy Python versions
# would fail with: SyntaxError: unqualified exec is not allowed

View File

@@ -113,7 +113,7 @@ gem5_citations = """@article{Binkert:2011:gem5,
Mohammad Alian and
Rico Amslinger and
Matteo Andreozzi and
Adri{\`{a}} Armejach and
Adri{\\`{a}} Armejach and
Nils Asmussen and
Srikant Bharadwaj and
Gabe Black and

View File

@@ -513,7 +513,7 @@ def main():
if os.name == "nt" and os.sep == "\\":
# If a Windows machine, we manually quote the string.
arg = arg.replace('"', '\\"')
if re.search("\s", args):
if re.search(r"\s", args):
# We quote args which have whitespace.
arg = '"' + arg + '"'
return arg
@@ -615,7 +615,7 @@ def main():
if not options.P:
sys.path = [os.path.dirname(sys.argv[0])] + sys.path
filename = sys.argv[0]
filedata = open(filename, "r").read()
filedata = open(filename).read()
filecode = compile(filedata, filename, "exec")
scope = {"__file__": filename, "__name__": "__m5_main__"}

View File

@@ -30,11 +30,11 @@ import sys
from optparse import *
class nodefault(object):
class nodefault:
pass
class splitter(object):
class splitter:
def __init__(self, split):
self.split = split

View File

@@ -101,7 +101,7 @@ class MetaParamValue(type):
# Dummy base class to identify types that are legitimate for SimObject
# parameters.
class ParamValue(object, metaclass=MetaParamValue):
class ParamValue(metaclass=MetaParamValue):
cmd_line_settable = False
# Generate the code needed as a prerequisite for declaring a C++
@@ -149,7 +149,7 @@ class ParamValue(object, metaclass=MetaParamValue):
# Regular parameter description.
class ParamDesc(object):
class ParamDesc:
def __init__(self, ptype_str, ptype, *args, **kwargs):
self.ptype_str = ptype_str
# remember ptype only if it is provided
@@ -298,8 +298,7 @@ class SimObjectVector(VectorParamValue):
# SimObjectVector directly.
def descendants(self):
for v in self:
for obj in v.descendants():
yield obj
yield from v.descendants()
def get_config_as_dict(self):
a = []
@@ -415,7 +414,7 @@ class VectorParamDesc(ParamDesc):
code("std::vector< ${{self.ptype.cxx_type}} > ${{self.name}};")
class ParamFactory(object):
class ParamFactory:
def __init__(self, param_desc_class, ptype_str=None):
self.param_desc_class = param_desc_class
self.ptype_str = ptype_str
@@ -966,7 +965,7 @@ class AddrRange(ParamValue):
if len(self.masks) == 0:
return f"{self.start}:{self.end}"
else:
return "%s:%s:%s:%s" % (
return "{}:{}:{}:{}".format(
self.start,
self.end,
self.intlvMatch,
@@ -1602,7 +1601,7 @@ class Enum(ParamValue, metaclass=MetaEnum):
def cxx_ini_parse(cls, code, src, dest, ret):
code("if (false) {")
for elem_name in cls.map.keys():
code('} else if (%s == "%s") {' % (src, elem_name))
code(f'}} else if ({src} == "{elem_name}") {{')
code.indent()
name = cls.__name__ if cls.enum_name is None else cls.enum_name
code(f"{dest} = {name if cls.is_class else 'enums'}::{elem_name};")
@@ -1970,7 +1969,7 @@ class MemoryBandwidth(float, ParamValue):
# make_param_value() above that lets these be assigned where a
# SimObject is required.
# only one copy of a particular node
class NullSimObject(object, metaclass=Singleton):
class NullSimObject(metaclass=Singleton):
_name = "Null"
def __call__(cls):
@@ -2036,7 +2035,7 @@ AllMemory = AddrRange(0, MaxAddr)
# Port reference: encapsulates a reference to a particular port on a
# particular SimObject.
class PortRef(object):
class PortRef:
def __init__(self, simobj, name, role, is_source):
assert isSimObject(simobj) or isSimObjectClass(simobj)
self.simobj = simobj
@@ -2206,7 +2205,7 @@ class VectorPortElementRef(PortRef):
# A reference to a complete vector-valued port (not just a single element).
# Can be indexed to retrieve individual VectorPortElementRef instances.
class VectorPortRef(object):
class VectorPortRef:
def __init__(self, simobj, name, role, is_source):
assert isSimObject(simobj) or isSimObjectClass(simobj)
self.simobj = simobj
@@ -2288,7 +2287,7 @@ class VectorPortRef(object):
# Port description object. Like a ParamDesc object, this represents a
# logical port in the SimObject class, not a particular port on a
# SimObject instance. The latter are represented by PortRef objects.
class Port(object):
class Port:
# Port("role", "description")
_compat_dict = {}
@@ -2379,12 +2378,12 @@ VectorSlavePort = VectorResponsePort
# 'Fake' ParamDesc for Port references to assign to the _pdesc slot of
# proxy objects (via set_param_desc()) so that proxy error messages
# make sense.
class PortParamDesc(object, metaclass=Singleton):
class PortParamDesc(metaclass=Singleton):
ptype_str = "Port"
ptype = Port
class DeprecatedParam(object):
class DeprecatedParam:
"""A special type for deprecated parameter variable names.
There are times when we need to change the name of parameter, but this

View File

@@ -45,7 +45,7 @@
import copy
class BaseProxy(object):
class BaseProxy:
def __init__(self, search_self, search_up):
self._search_self = search_self
self._search_up = search_up
@@ -272,7 +272,7 @@ def isproxy(obj):
return False
class ProxyFactory(object):
class ProxyFactory:
def __init__(self, search_self, search_up):
self.search_self = search_self
self.search_up = search_up

View File

@@ -82,7 +82,7 @@ def dot_create_nodes(simNode, callgraph):
label = "root"
else:
label = simNode._name
full_path = re.sub("\.", "_", simNode.path())
full_path = re.sub(r"\.", "_", simNode.path())
# add class name under the label
label = '"' + label + " \\n: " + simNode.__class__.__name__ + '"'
@@ -109,7 +109,7 @@ def dot_create_edges(simNode, callgraph):
for port_name in simNode._ports.keys():
port = simNode._port_refs.get(port_name, None)
if port != None:
full_path = re.sub("\.", "_", simNode.path())
full_path = re.sub(r"\.", "_", simNode.path())
full_port_name = full_path + "_" + port_name
port_node = dot_create_node(simNode, full_port_name, port_name)
# create edges
@@ -128,7 +128,7 @@ def dot_create_edges(simNode, callgraph):
def dot_add_edge(simNode, callgraph, full_port_name, port):
peer = port.peer
full_peer_path = re.sub("\.", "_", peer.simobj.path())
full_peer_path = re.sub(r"\.", "_", peer.simobj.path())
full_peer_port_name = full_peer_path + "_" + peer.name
# Each edge is encountered twice, once for each peer. We only want one
@@ -290,9 +290,9 @@ def dot_rgb_to_html(r, g, b):
# We need to create all of the clock domains. We abuse the alpha channel to get
# the correct domain colouring.
def dot_add_clk_domain(c_dom, v_dom):
label = '"' + str(c_dom) + "\ :\ " + str(v_dom) + '"'
label = re.sub("\.", "_", str(label))
full_path = re.sub("\.", "_", str(c_dom))
label = '"' + str(c_dom) + r"\ :\ " + str(v_dom) + '"'
label = re.sub(r"\.", "_", str(label))
full_path = re.sub(r"\.", "_", str(c_dom))
return pydot.Cluster(
full_path,
shape="box",
@@ -311,7 +311,7 @@ def dot_create_dvfs_nodes(simNode, callgraph, domain=None):
label = "root"
else:
label = simNode._name
full_path = re.sub("\.", "_", simNode.path())
full_path = re.sub(r"\.", "_", simNode.path())
# add class name under the label
label = '"' + label + " \\n: " + simNode.__class__.__name__ + '"'

View File

@@ -86,7 +86,7 @@ class FdtPropertyBytes(pyfdt.FdtPropertyBytes):
super().__init__(name, values)
class FdtState(object):
class FdtState:
"""Class for maintaining state while recursively generating a flattened
device tree. The state tracks address, size and CPU address cell sizes, and
maintains a dictionary of allocated phandles."""
@@ -270,7 +270,7 @@ class Fdt(pyfdt.Fdt):
with open(filename, "wb") as f:
f.write(self.to_dtb())
return filename
except IOError:
except OSError:
raise RuntimeError("Failed to open DTB output file")
def writeDtsFile(self, filename):
@@ -280,5 +280,5 @@ class Fdt(pyfdt.Fdt):
with open(filename, "w") as f:
f.write(self.to_dts())
return filename
except IOError:
except OSError:
raise RuntimeError("Failed to open DTS output file")

View File

@@ -27,7 +27,7 @@
__all__ = ["multidict"]
class multidict(object):
class multidict:
def __init__(self, parent={}, **kwargs):
self.local = dict(**kwargs)
self.parent = parent
@@ -80,8 +80,7 @@ class multidict(object):
return key in self
def items(self):
for item in self.next():
yield item
yield from self.next()
def keys(self):
for key, value in self.next():

View File

@@ -36,7 +36,7 @@
from abc import *
class PyBindExport(object, metaclass=ABCMeta):
class PyBindExport(metaclass=ABCMeta):
@abstractmethod
def export(self, code, cname):
pass

View File

@@ -84,7 +84,7 @@ except:
cap_string = null_cap_string
class ColorStrings(object):
class ColorStrings:
def __init__(self, cap_string):
for i, c in enumerate(color_names):
setattr(self, c, cap_string("setaf", i))