misc: Use python 3's argumentless super().

When calling a method in a superclass, you can/should use the super()
method to get a reference to that class. The python 2 version of that
method takes two parameters, the current class name, and the "self"
instance. The python 3 version takes no arguments. This is better for a
at least three reasons.

First, this version is less verbose because you don't have to specify
any arguments.

Second, you don't have to remember which argument goes where (I always
have to look it up), and you can't accidentally use the wrong class
name, or forget to update it if you copy code from a different class.

Third, this version will work correctly if you use a class decorator.
I don't know exactly how the mechanics of this work, but it is referred
to in a comment on this stackoverflow question:

https://stackoverflow.com/questions/681953/how-to-decorate-a-class

Change-Id: I427737c8f767e80da86cd245642e3b057121bc3b
Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/52224
Reviewed-by: Gabe Black <gabe.black@gmail.com>
Maintainer: Gabe Black <gabe.black@gmail.com>
Tested-by: kokoro <noreply+kokoro@google.com>
This commit is contained in:
Gabe Black
2021-10-28 16:16:07 -07:00
parent e4cff7b5ca
commit ba5f68db3d
142 changed files with 301 additions and 370 deletions

View File

@@ -450,7 +450,7 @@ class MetaSimObject(type):
if 'cxx_template_params' not in value_dict:
value_dict['cxx_template_params'] = []
cls_dict['_value_dict'] = value_dict
cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
cls = super().__new__(mcls, name, bases, cls_dict)
if 'type' in value_dict:
allClasses[name] = cls
return cls
@@ -459,7 +459,7 @@ class MetaSimObject(type):
def __init__(cls, name, bases, dict):
# calls type.__init__()... I think that's a no-op, but leave
# it here just in case it's not.
super(MetaSimObject, cls).__init__(name, bases, dict)
super().__init__(name, bases, dict)
# initialize required attributes
@@ -1147,7 +1147,7 @@ class ParamInfo(object):
class SimObjectCliWrapperException(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
super().__init__(message)
class SimObjectCliWrapper(object):
"""

View File

@@ -51,7 +51,7 @@ class EventWrapper(Event):
"""Helper class to wrap callable objects in an Event base class"""
def __init__(self, func, **kwargs):
super(EventWrapper, self).__init__(**kwargs)
super().__init__(**kwargs)
if not callable(func):
raise RuntimeError("Can't wrap '%s', object is not callable" % \
@@ -68,7 +68,7 @@ class EventWrapper(Event):
class ProgressEvent(Event):
def __init__(self, eventq, period):
super(ProgressEvent, self).__init__()
super().__init__()
self.period = int(period)
self.eventq = eventq
self.eventq.schedule(self, m5.curTick() + self.period)

View File

@@ -133,8 +133,4 @@ class Vector(Group):
https://gem5.atlassian.net/browse/GEM5-867.
"""
def __init__(self, scalar_map: Mapping[str,Scalar]):
super(Vector, self).__init__(
type="Vector",
time_conversion=None,
**scalar_map,
)
super().__init__(type="Vector", time_conversion=None, **scalar_map)

View File

@@ -47,9 +47,7 @@ class JsonLoader(json.JSONDecoder):
"""
def __init__(self):
super(JsonLoader, self).__init__(self,
object_hook=self.__json_to_simstat
)
super().__init__(self, object_hook=self.__json_to_simstat)
def __json_to_simstat(self, d: dict) -> Union[SimStat,Statistic,Group]:
if 'type' in d:

View File

@@ -62,13 +62,8 @@ class Scalar(Statistic):
unit: Optional[str] = None,
description: Optional[str] = None,
datatype: Optional[StorageType] = None):
super(Scalar, self).__init__(
value=value,
type="Scalar",
unit=unit,
description=description,
datatype=datatype,
)
super().__init__(value=value, type="Scalar", unit=unit,
description=description, datatype=datatype)
class BaseScalarVector(Statistic):
"""
@@ -81,13 +76,8 @@ class BaseScalarVector(Statistic):
unit: Optional[str] = None,
description: Optional[str] = None,
datatype: Optional[StorageType] = None):
super(BaseScalarVector, self).__init__(
value=list(value),
type=type,
unit=unit,
description=description,
datatype=datatype,
)
super().__init__(value=list(value), type=type, unit=unit,
description=description, datatype=datatype)
def mean(self) -> float:
"""
@@ -150,13 +140,8 @@ class Distribution(BaseScalarVector):
unit: Optional[str] = None,
description: Optional[str] = None,
datatype: Optional[StorageType] = None):
super(Distribution, self).__init__(
value=value,
type="Distribution",
unit=unit,
description=description,
datatype=datatype,
)
super().__init__(value=value, type="Distribution", unit=unit,
description=description, datatype=datatype)
self.min = min
self.max = max
@@ -190,13 +175,8 @@ class Accumulator(BaseScalarVector):
unit: Optional[str] = None,
description: Optional[str] = None,
datatype: Optional[StorageType] = None):
super(Accumulator, self).__init__(
value=value,
type="Accumulator",
unit=unit,
description=description,
datatype=datatype,
)
super().__init__(value=value, type="Accumulator", unit=unit,
description=description, datatype=datatype)
self._count = count
self.min = min

View File

@@ -106,23 +106,23 @@ class OptionParser(dict):
def __getattr__(self, attr):
if attr.startswith('_'):
return super(OptionParser, self).__getattribute__(attr)
return super().__getattribute__(attr)
if attr in self:
return self[attr]
return super(OptionParser, self).__getattribute__(attr)
return super().__getattribute__(attr)
def __setattr__(self, attr, value):
if attr.startswith('_'):
super(OptionParser, self).__setattr__(attr, value)
super().__setattr__(attr, value)
elif attr in self._allopts:
defaults = { attr : value }
self.set_defaults(**defaults)
if attr in self:
self[attr] = value
else:
super(OptionParser, self).__setattr__(attr, value)
super().__setattr__(attr, value)
def parse_args(self):
opts,args = self._optparse.parse_args()

View File

@@ -81,7 +81,7 @@ allParams = {}
class MetaParamValue(type):
def __new__(mcls, name, bases, dct):
cls = super(MetaParamValue, mcls).__new__(mcls, name, bases, dct)
cls = super().__new__(mcls, name, bases, dct)
if name in allParams:
warn("%s already exists in allParams. This may be caused by the " \
"Python 2.7 compatibility layer." % (name, ))
@@ -301,7 +301,7 @@ class SimObjectVector(VectorParamValue):
warn("SimObject %s already has a parent" % value.get_name() +\
" that is being overwritten by a SimObjectVector")
value.set_parent(val.get_parent(), val._name)
super(SimObjectVector, self).__setitem__(key, value)
super().__setitem__(key, value)
# Enumerate the params of each member of the SimObject vector. Creates
# strings that will allow indexing into the vector by the python code and
@@ -347,7 +347,7 @@ class VectorParamDesc(ParamDesc):
# how to set this vector parameter in the absence of a default
# value.
def example_str(self):
s = super(VectorParamDesc, self).example_str()
s = super().example_str()
help_str = "[" + s + "," + s + ", ...]"
return help_str
@@ -548,7 +548,7 @@ class NumericParamValue(ParamValue):
# Metaclass for bounds-checked integer parameters. See CheckedInt.
class CheckedIntType(MetaParamValue):
def __init__(cls, name, bases, dict):
super(CheckedIntType, cls).__init__(name, bases, dict)
super().__init__(name, bases, dict)
# CheckedInt is an abstract base class, so we actually don't
# want to do any processing on it... the rest of this code is
@@ -1094,7 +1094,7 @@ class IpNetmask(IpAddress):
return value
def __str__(self):
return "%s/%d" % (super(IpNetmask, self).__str__(), self.netmask)
return "%s/%d" % (super().__str__(), self.netmask)
def __eq__(self, other):
if isinstance(other, IpNetmask):
@@ -1168,7 +1168,7 @@ class IpWithPort(IpAddress):
return value
def __str__(self):
return "%s:%d" % (super(IpWithPort, self).__str__(), self.port)
return "%s:%d" % (super().__str__(), self.port)
def __eq__(self, other):
if isinstance(other, IpWithPort):
@@ -1287,7 +1287,7 @@ allEnums = {}
class MetaEnum(MetaParamValue):
def __new__(mcls, name, bases, dict):
cls = super(MetaEnum, mcls).__new__(mcls, name, bases, dict)
cls = super().__new__(mcls, name, bases, dict)
allEnums[name] = cls
return cls
@@ -1316,7 +1316,7 @@ class MetaEnum(MetaParamValue):
else:
cls.cxx_type = 'enums::%s' % name
super(MetaEnum, cls).__init__(name, bases, init_dict)
super().__init__(name, bases, init_dict)
# Generate C++ class declaration for this enum type.
# Note that we wrap the enum in a class/struct to act as a namespace,
@@ -1694,33 +1694,33 @@ class Voltage(Float):
def __new__(cls, value):
value = convert.toVoltage(value)
return super(cls, Voltage).__new__(cls, value)
return super().__new__(cls, value)
def __init__(self, value):
value = convert.toVoltage(value)
super(Voltage, self).__init__(value)
super().__init__(value)
class Current(Float):
ex_str = "1mA"
def __new__(cls, value):
value = convert.toCurrent(value)
return super(cls, Current).__new__(cls, value)
return super().__new__(cls, value)
def __init__(self, value):
value = convert.toCurrent(value)
super(Current, self).__init__(value)
super().__init__(value)
class Energy(Float):
ex_str = "1pJ"
def __new__(cls, value):
value = convert.toEnergy(value)
return super(cls, Energy).__new__(cls, value)
return super().__new__(cls, value)
def __init__(self, value):
value = convert.toEnergy(value)
super(Energy, self).__init__(value)
super().__init__(value)
class Temperature(ParamValue):
cxx_type = 'Temperature'
@@ -1770,7 +1770,7 @@ class NetworkBandwidth(float,ParamValue):
def __new__(cls, value):
# convert to bits per second
val = convert.toNetworkBandwidth(value)
return super(cls, NetworkBandwidth).__new__(cls, val)
return super().__new__(cls, val)
def __str__(self):
return str(self.val)
@@ -1809,7 +1809,7 @@ class MemoryBandwidth(float,ParamValue):
def __new__(cls, value):
# convert to bytes per second
val = convert.toMemoryBandwidth(value)
return super(cls, MemoryBandwidth).__new__(cls, val)
return super().__new__(cls, val)
def __call__(self, value):
val = convert.toMemoryBandwidth(value)
@@ -2180,13 +2180,12 @@ Port.compat('GEM5 REQUESTOR', 'GEM5 RESPONDER')
class RequestPort(Port):
# RequestPort("description")
def __init__(self, desc):
super(RequestPort, self).__init__(
'GEM5 REQUESTOR', desc, is_source=True)
super().__init__('GEM5 REQUESTOR', desc, is_source=True)
class ResponsePort(Port):
# ResponsePort("description")
def __init__(self, desc):
super(ResponsePort, self).__init__('GEM5 RESPONDER', desc)
super().__init__('GEM5 RESPONDER', desc)
# VectorPort description object. Like Port, but represents a vector
# of connections (e.g., as on a XBar).
@@ -2197,13 +2196,12 @@ class VectorPort(Port):
class VectorRequestPort(VectorPort):
# VectorRequestPort("description")
def __init__(self, desc):
super(VectorRequestPort, self).__init__(
'GEM5 REQUESTOR', desc, is_source=True)
super().__init__('GEM5 REQUESTOR', desc, is_source=True)
class VectorResponsePort(VectorPort):
# VectorResponsePort("description")
def __init__(self, desc):
super(VectorResponsePort, self).__init__('GEM5 RESPONDER', desc)
super().__init__('GEM5 RESPONDER', desc)
# Old names, maintained for compatibility.
MasterPort = RequestPort

View File

@@ -63,7 +63,7 @@ class BaseProxy(object):
if not attr.startswith('_'):
raise AttributeError(
"cannot set attribute '%s' on proxy object" % attr)
super(BaseProxy, self).__setattr__(attr, value)
super().__setattr__(attr, value)
def _gen_op(operation):
def op(self, operand):
@@ -163,14 +163,14 @@ class BaseProxy(object):
class AttrProxy(BaseProxy):
def __init__(self, search_self, search_up, attr):
super(AttrProxy, self).__init__(search_self, search_up)
super().__init__(search_self, search_up)
self._attr = attr
self._modifiers = []
def __getattr__(self, attr):
# python uses __bases__ internally for inheritance
if attr.startswith('_'):
return super(AttrProxy, self).__getattr__(self, attr)
return super().__getattr__(self, attr)
if hasattr(self, '_pdesc'):
raise AttributeError("Attribute reference on bound proxy "
f"({self}.{attr})")

View File

@@ -76,7 +76,7 @@ class Singleton(type):
if hasattr(cls, '_instance'):
return cls._instance
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
def addToPath(path):

View File

@@ -31,17 +31,17 @@ class attrdict(dict):
def __getattr__(self, attr):
if attr in self:
return self.__getitem__(attr)
return super(attrdict, self).__getattribute__(attr)
return super().__getattribute__(attr)
def __setattr__(self, attr, value):
if attr in dir(self) or attr.startswith('_'):
return super(attrdict, self).__setattr__(attr, value)
return super().__setattr__(attr, value)
return self.__setitem__(attr, value)
def __delattr__(self, attr):
if attr in self:
return self.__delitem__(attr)
return super(attrdict, self).__delattr__(attr)
return super().__delattr__(attr)
def __getstate__(self):
return dict(self)
@@ -54,7 +54,7 @@ class multiattrdict(attrdict):
nested dictionaries."""
def __getattr__(self, attr):
try:
return super(multiattrdict, self).__getattr__(attr)
return super().__getattr__(attr)
except AttributeError:
if attr.startswith('_'):
raise
@@ -67,7 +67,7 @@ class optiondict(attrdict):
"""Modify attrdict so that a missing attribute just returns None"""
def __getattr__(self, attr):
try:
return super(optiondict, self).__getattr__(attr)
return super().__getattr__(attr)
except AttributeError:
return None

View File

@@ -53,7 +53,7 @@ class FdtPropertyWords(pyfdt.FdtPropertyWords):
# Make sure all values are ints (use automatic base detection if the
# type is str)
words = [int(w, base=0) if type(w) == str else int(w) for w in words]
super(FdtPropertyWords, self).__init__(name, words)
super().__init__(name, words)
class FdtPropertyStrings(pyfdt.FdtPropertyStrings):
"""Create a property with string values."""
@@ -62,7 +62,7 @@ class FdtPropertyStrings(pyfdt.FdtPropertyStrings):
if type(strings) == str:
strings = [strings]
strings = [str(string) for string in strings] # Make all values strings
super(FdtPropertyStrings, self).__init__(name, strings)
super().__init__(name, strings)
class FdtPropertyBytes(pyfdt.FdtPropertyBytes):
"""Create a property with integer (8-bit signed) values."""
@@ -74,7 +74,7 @@ class FdtPropertyBytes(pyfdt.FdtPropertyBytes):
# type is str)
values = [int(v, base=0)
if isinstance(v, str) else int(v) for v in values]
super(FdtPropertyBytes, self).__init__(name, values)
super().__init__(name, values)
class FdtState(object):
"""Class for maintaining state while recursively generating a flattened
@@ -172,7 +172,7 @@ class FdtNode(pyfdt.FdtNode):
def __init__(self, name, obj=None):
"""Create a new node and immediately set the phandle property, if obj
is supplied"""
super(FdtNode, self).__init__(name)
super().__init__(name)
if obj != None:
self.appendPhandle(obj)
@@ -198,7 +198,7 @@ class FdtNode(pyfdt.FdtNode):
item.merge(subnode)
subnode = item
super(FdtNode, self).append(subnode)
super().append(subnode)
def appendList(self, subnode_list):
"""Append all properties/nodes in the iterable."""
@@ -245,7 +245,7 @@ class Fdt(pyfdt.Fdt):
def add_rootnode(self, rootnode, prenops=None, postnops=None):
"""First sort the device tree, so that properties are before nodes."""
rootnode = self.sortNodes(rootnode)
super(Fdt, self).add_rootnode(rootnode, prenops, postnops)
super().add_rootnode(rootnode, prenops, postnops)
def writeDtbFile(self, filename):
"""Convert the device tree to DTB and write to a file."""