Skip to content

Commit 87be5e1

Browse files
committed
Bulk-replace cls.__name__ with cls.__qualname__.
In most cases these two attributes contain the same string, however, in case of nested or locally defined classes, the latter is important for disambiguation. A few instances of `mod.__name__` remain in the codebase.
1 parent 42d90a3 commit 87be5e1

17 files changed

+55
-57
lines changed

amaranth/_unused.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __del__(self):
3232
return
3333
if hasattr(self, "_MustUse__used") and not self._MustUse__used:
3434
if get_linter_option(self._MustUse__context["filename"],
35-
self._MustUse__warning.__name__, bool, True):
35+
self._MustUse__warning.__qualname__, bool, True):
3636
warnings.warn_explicit(
3737
f"{self!r} created but never used", self._MustUse__warning,
3838
**self._MustUse__context)

amaranth/_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def union(i, start=None):
4444
def final(cls):
4545
def init_subclass():
4646
raise TypeError("Subclassing {}.{} is not supported"
47-
.format(cls.__module__, cls.__name__))
47+
.format(cls.__module__, cls.__qualname__))
4848
cls.__init_subclass__ = init_subclass
4949
return cls
5050

amaranth/build/plat.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,15 @@ def __init__(self):
4040
def default_clk_constraint(self):
4141
if self.default_clk is None:
4242
raise AttributeError("Platform '{}' does not define a default clock"
43-
.format(type(self).__name__))
43+
.format(type(self).__qualname__))
4444
return self.lookup(self.default_clk).clock
4545

4646
@property
4747
def default_clk_frequency(self):
4848
constraint = self.default_clk_constraint
4949
if constraint is None:
5050
raise AttributeError("Platform '{}' does not constrain its default clock"
51-
.format(type(self).__name__))
51+
.format(type(self).__qualname__))
5252
return constraint.frequency
5353

5454
def add_file(self, filename, content):
@@ -173,7 +173,7 @@ def toolchain_program(self, products, name, **kwargs):
173173
Extract bitstream for fragment ``name`` from ``products`` and download it to a target.
174174
"""
175175
raise NotImplementedError("Platform '{}' does not support programming"
176-
.format(type(self).__name__))
176+
.format(type(self).__qualname__))
177177

178178

179179
class TemplatedPlatform(Platform):
@@ -244,7 +244,7 @@ def _extract_override(var, *, expected_type):
244244
if issubclass(expected_type, str) and not isinstance(kwarg, str) and isinstance(kwarg, Iterable):
245245
kwarg = " ".join(kwarg)
246246
if not isinstance(kwarg, expected_type) and not expected_type is None:
247-
raise TypeError(f"Override '{var}' must be a {expected_type.__name__}, not {kwarg!r}")
247+
raise TypeError(f"Override '{var}' must be a {expected_type.__qualname__}, not {kwarg!r}")
248248
return kwarg
249249
else:
250250
return jinja2.Undefined(name=var)

amaranth/hdl/_ast.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -244,16 +244,16 @@ def __init__(self, *args, **kwargs):
244244

245245
def __init_subclass__(cls, **kwargs):
246246
if cls.as_shape is ShapeCastable.as_shape:
247-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
247+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ShapeCastable' must override "
248248
f"the 'as_shape' method")
249249
if cls.const is ShapeCastable.const:
250-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
250+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ShapeCastable' must override "
251251
f"the 'const' method")
252252
if cls.__call__ is ShapeCastable.__call__:
253-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
253+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ShapeCastable' must override "
254254
f"the '__call__' method")
255255
if cls.from_bits is ShapeCastable.from_bits:
256-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ShapeCastable' must override "
256+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ShapeCastable' must override "
257257
f"the 'from_bits' method")
258258

259259
# The signatures and definitions of these methods are weird because they are present here for
@@ -1400,10 +1400,10 @@ def __init__(self, *args, **kwargs):
14001400

14011401
def __init_subclass__(cls, **kwargs):
14021402
if cls.as_value is ValueCastable.as_value:
1403-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ValueCastable' must override "
1403+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ValueCastable' must override "
14041404
"the 'as_value' method")
14051405
if cls.shape is ValueCastable.shape:
1406-
raise TypeError(f"Class '{cls.__name__}' deriving from 'ValueCastable' must override "
1406+
raise TypeError(f"Class '{cls.__qualname__}' deriving from 'ValueCastable' must override "
14071407
"the 'shape' method")
14081408

14091409
# The signatures and definitions of these methods are weird because they are present here for
@@ -2065,12 +2065,12 @@ def __init__(self, shape=None, *, name=None, init=None, reset=None, reset_less=F
20652065
if isinstance(orig_shape, ShapeCastable):
20662066
self._format = orig_shape.format(orig_shape(self), "")
20672067
elif isinstance(orig_shape, type) and issubclass(orig_shape, Enum):
2068-
self._format = Format.Enum(self, orig_shape, name=orig_shape.__name__)
2068+
self._format = Format.Enum(self, orig_shape, name=orig_shape.__qualname__)
20692069
else:
20702070
self._format = Format("{}", self)
20712071

20722072
if isinstance(decoder, type) and issubclass(decoder, Enum):
2073-
self._format = Format.Enum(self, decoder, name=decoder.__name__)
2073+
self._format = Format.Enum(self, decoder, name=decoder.__qualname__)
20742074

20752075
self._decoder = decoder
20762076

@@ -3185,7 +3185,7 @@ def __len__(self):
31853185

31863186
def __repr__(self):
31873187
pairs = [f"({k!r}, {v!r})" for k, v in self.items()]
3188-
return "{}.{}([{}])".format(type(self).__module__, type(self).__name__,
3188+
return "{}.{}([{}])".format(type(self).__module__, type(self).__qualname__,
31893189
", ".join(pairs))
31903190

31913191

@@ -3217,7 +3217,7 @@ def __len__(self):
32173217
return len(self._storage)
32183218

32193219
def __repr__(self):
3220-
return "{}.{}({})".format(type(self).__module__, type(self).__name__,
3220+
return "{}.{}({})".format(type(self).__module__, type(self).__qualname__,
32213221
", ".join(repr(x) for x in self))
32223222

32233223

@@ -3247,7 +3247,7 @@ def __lt__(self, other):
32473247
return self._intern < other._intern
32483248

32493249
def __repr__(self):
3250-
return f"<{__name__}.SignalKey {self.signal!r}>"
3250+
return f"<{__qualname__}.SignalKey {self.signal!r}>"
32513251

32523252

32533253
class SignalDict(_MappedKeyDict):

amaranth/hdl/_dsl.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,9 @@ def __init__(self, builder, depth):
144144
def __getattr__(self, name):
145145
if name in ("comb", "sync"):
146146
raise AttributeError("'{}' object has no attribute '{}'; did you mean 'd.{}'?"
147-
.format(type(self).__name__, name, name))
147+
.format(type(self).__qualname__, name, name))
148148
raise AttributeError("'{}' object has no attribute '{}'"
149-
.format(type(self).__name__, name))
149+
.format(type(self).__qualname__, name))
150150

151151

152152
class _ModuleBuilderSubmodules:

amaranth/hdl/_nir.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ def traverse(net):
465465
elif isinstance(obj, Operator):
466466
obj = f"operator {obj.operator}"
467467
else:
468-
obj = f"cell {obj.__class__.__name__}"
468+
obj = f"cell {obj.__class__.__qualname__}"
469469
src_loc = "<unknown>:0" if src_loc is None else f"{src_loc[0]}:{src_loc[1]}"
470470
msg.append(f" {src_loc}: {obj} bit {bit}\n")
471471
raise CombinationalCycle("".join(msg))
@@ -656,7 +656,7 @@ class Operator(Cell):
656656
657657
The ternary operators are:
658658
659-
- 'm': multiplexer, first input needs to have width of 1, second and third operand need to have
659+
- 'm': multiplexer, first input needs to have width of 1, second and third operand need to have
660660
the same width as output; implements arg0 ? arg1 : arg2
661661
662662
Attributes

amaranth/lib/cdc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def elaborate(self, platform):
9696
if self._max_input_delay is not None:
9797
raise NotImplementedError("Platform '{}' does not support constraining input delay "
9898
"for FFSynchronizer"
99-
.format(type(platform).__name__))
99+
.format(type(platform).__qualname__))
100100

101101
m = Module()
102102
flops = [Signal(self.i.shape(), name=f"stage{index}",
@@ -170,7 +170,7 @@ def elaborate(self, platform):
170170
if self._max_input_delay is not None:
171171
raise NotImplementedError("Platform '{}' does not support constraining input delay "
172172
"for AsyncFFSynchronizer"
173-
.format(type(platform).__name__))
173+
.format(type(platform).__qualname__))
174174

175175
m = Module()
176176
m.domains += ClockDomain("async_ff", async_reset=True)

amaranth/lib/data.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -911,7 +911,7 @@ def __and__(self, other):
911911
__rxor__ = __and__
912912

913913
def __repr__(self):
914-
return f"{self.__class__.__name__}({self.__layout!r}, {self.__target!r})"
914+
return f"{self.__class__.__qualname__}({self.__layout!r}, {self.__target!r})"
915915

916916

917917
class Const(ValueCastable):
@@ -1146,7 +1146,7 @@ def __and__(self, other):
11461146
__rxor__ = __and__
11471147

11481148
def __repr__(self):
1149-
return f"{self.__class__.__name__}({self.__layout!r}, {self.__target!r})"
1149+
return f"{self.__class__.__qualname__}({self.__layout!r}, {self.__target!r})"
11501150

11511151

11521152
class _AggregateMeta(ShapeCastable, type):

amaranth/lib/enum.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def from_bits(cls, bits):
178178
def format(cls, value, format_spec):
179179
if format_spec != "":
180180
raise ValueError(f"Format specifier {format_spec!r} is not supported for enums")
181-
return Format.Enum(value, cls, name=cls.__name__)
181+
return Format.Enum(value, cls, name=cls.__qualname__)
182182

183183

184184
# In 3.11, Python renamed EnumMeta to EnumType. Like Python itself, we support both for
@@ -310,7 +310,7 @@ def __ne__(self, other):
310310
return self.target != other.target
311311

312312
def __repr__(self):
313-
return f"{type(self).__name__}({self.enum.__name__}, {self.target!r})"
313+
return f"{type(self).__qualname__}({self.enum.__qualname__}, {self.target!r})"
314314

315315

316316
class FlagView(EnumView):

amaranth/lib/wiring.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1198,7 +1198,7 @@ def __repr__(self):
11981198
attrs = ''.join(f", {name}={value!r}"
11991199
for name, value in self.__dict__.items()
12001200
if name != "signature")
1201-
return f'<{type(self).__name__}: {self.signature}{attrs}>'
1201+
return f'<{type(self).__qualname__}: {self.signature}{attrs}>'
12021202

12031203

12041204
# To reduce API surface area `FlippedInterface` is made final. This restriction could be lifted

amaranth/rpc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def _serve_yosys(modules):
7676
rtlil_text = rtlil.convert(elaboratable, name=module_name, ports=ports)
7777
response = {"frontend": "ilang", "source": rtlil_text}
7878
except Exception as error:
79-
response = {"error": f"{type(error).__name__}: {str(error)}"}
79+
response = {"error": f"{type(error).__qualname__}: {str(error)}"}
8080

8181
else:
8282
return {"error": "Unrecognized method {!r}".format(request["method"])}

amaranth/vendor/_xilinx.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1236,7 +1236,7 @@ def get_ff_sync(self, ff_sync):
12361236
elif ff_sync._max_input_delay is not None:
12371237
raise NotImplementedError("Platform '{}' does not support constraining input delay "
12381238
"for FFSynchronizer"
1239-
.format(type(self).__name__))
1239+
.format(type(self).__qualname__))
12401240
for i, o in zip((ff_sync.i, *flops), flops):
12411241
m.d[ff_sync._o_domain] += o.eq(i)
12421242
m.d.comb += ff_sync.o.eq(flops[-1])
@@ -1284,7 +1284,7 @@ def get_async_ff_sync(self, async_ff_sync):
12841284
elif async_ff_sync._max_input_delay is not None:
12851285
raise NotImplementedError("Platform '{}' does not support constraining input delay "
12861286
"for AsyncFFSynchronizer"
1287-
.format(type(self).__name__))
1287+
.format(type(self).__qualname__))
12881288

12891289
for i, o in zip((0, *flops_q), flops_d):
12901290
m.d.comb += o.eq(i)

tests/test_back_rtlil.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2024,7 +2024,7 @@ class MyEnum(enum.Enum, shape=unsigned(2)):
20242024
attribute \generator "Amaranth"
20252025
attribute \top 1
20262026
module \top
2027-
attribute \enum_base_type "MyEnum"
2027+
attribute \enum_base_type "DetailTestCase.test_enum.<locals>.MyEnum"
20282028
attribute \enum_value_00 "A"
20292029
attribute \enum_value_01 "B"
20302030
attribute \enum_value_10 "C"
@@ -2052,7 +2052,7 @@ class Meow(data.Struct):
20522052
attribute \top 1
20532053
module \top
20542054
wire width 13 input 0 \sig
2055-
attribute \enum_base_type "MyEnum"
2055+
attribute \enum_base_type "DetailTestCase.test_struct.<locals>.MyEnum"
20562056
attribute \enum_value_00 "A"
20572057
attribute \enum_value_01 "B"
20582058
attribute \enum_value_10 "C"

tests/test_hdl_ast.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ def from_bits(self, bits):
185185
class ShapeCastableTestCase(FHDLTestCase):
186186
def test_no_override(self):
187187
with self.assertRaisesRegex(TypeError,
188-
r"^Class 'MockShapeCastableNoOverride' deriving from 'ShapeCastable' must "
188+
r"^Class '.+\.MockShapeCastableNoOverride' deriving from 'ShapeCastable' must "
189189
r"override the 'as_shape' method$"):
190190
class MockShapeCastableNoOverride(ShapeCastable):
191191
def __init__(self):
@@ -509,7 +509,7 @@ def __init__(self, value):
509509

510510
def shape(self):
511511
return MockConstShape()
512-
512+
513513
def as_value(self):
514514
return Const(self.value, 8)
515515

@@ -1308,7 +1308,7 @@ class Color(Enum):
13081308
BLUE = 2
13091309
s = Signal(decoder=Color)
13101310
self.assertEqual(s.decoder, Color)
1311-
self.assertRepr(s._format, "(format-enum (sig s) 'Color' (1 'RED') (2 'BLUE'))")
1311+
self.assertRepr(s._format, f"(format-enum (sig s) '{Color.__qualname__}' (1 'RED') (2 'BLUE'))")
13121312

13131313
def test_enum(self):
13141314
s1 = Signal(UnsignedEnum)
@@ -1481,14 +1481,14 @@ def __getattr__(self, attr):
14811481
class ValueCastableTestCase(FHDLTestCase):
14821482
def test_no_override(self):
14831483
with self.assertRaisesRegex(TypeError,
1484-
r"^Class 'MockValueCastableNoOverrideAsValue' deriving from 'ValueCastable' must "
1484+
r"^Class '.+\.MockValueCastableNoOverrideAsValue' deriving from 'ValueCastable' must "
14851485
r"override the 'as_value' method$"):
14861486
class MockValueCastableNoOverrideAsValue(ValueCastable):
14871487
def __init__(self):
14881488
pass
14891489

14901490
with self.assertRaisesRegex(TypeError,
1491-
r"^Class 'MockValueCastableNoOverrideShapec' deriving from 'ValueCastable' must "
1491+
r"^Class '.+\.MockValueCastableNoOverrideShapec' deriving from 'ValueCastable' must "
14921492
r"override the 'shape' method$"):
14931493
class MockValueCastableNoOverrideShapec(ValueCastable):
14941494
def __init__(self):

tests/test_hdl_ir.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3416,15 +3416,15 @@ class MyEnum(enum.Enum, shape=unsigned(2)):
34163416
])
34173417
self.assertEqual(nl.signal_fields[s1.as_value()], {
34183418
(): SignalField(nl.signals[s1.as_value()], signed=False),
3419-
('a',): SignalField(nl.signals[s1.as_value()][0:2], signed=False, enum_name="MyEnum", enum_variants={
3419+
('a',): SignalField(nl.signals[s1.as_value()][0:2], signed=False, enum_name=MyEnum.__qualname__, enum_variants={
34203420
0: "A",
34213421
1: "B",
34223422
2: "C",
34233423
}),
34243424
('b',): SignalField(nl.signals[s1.as_value()][2:5], signed=True)
34253425
})
34263426
self.assertEqual(nl.signal_fields[s2.as_value()], {
3427-
(): SignalField(nl.signals[s2.as_value()], signed=False, enum_name="MyEnum", enum_variants={
3427+
(): SignalField(nl.signals[s2.as_value()], signed=False, enum_name=MyEnum.__qualname__, enum_variants={
34283428
0: "A",
34293429
1: "B",
34303430
2: "C",
@@ -3515,4 +3515,4 @@ def test_require_renamed(self):
35153515
m.submodules += DomainRenamer("test")(RequirePosedge("sync"))
35163516
with self.assertRaisesRegex(DomainRequirementFailed,
35173517
r"^Domain test has a negedge clock, but posedge clock is required by top.U\$0 at .*$"):
3518-
Fragment.get(m, None).prepare()
3518+
Fragment.get(m, None).prepare()

0 commit comments

Comments
 (0)