[Tutor] use of dict() function

Peter Otten __peter__ at web.de
Wed Jun 12 04:03:54 EDT 2024


On 03/06/2024 04:44, Alex Kleider wrote:

You may have figured it out in the mean time, but note that

> class Rec1(dict):
>      def __init__(self, rec):
>          self = dict(rec)

assigning to self has no effect (on the class). self is just a name that
you can bind anything to:

 >>> class Stuff:
	def __init__(self):
		print(f"before: {self})"
		self = 42
		print(f"after: {self}")

SyntaxError: invalid syntax
 >>> class Stuff:
	def __init__(self):
		print(f"before: {self})")
		self = 42
		print(f"after: {self}")


 >>> Stuff()
before: <__main__.Stuff object at 0x02BDD5B0>)
after: 42
<__main__.Stuff object at 0x02BDD5B0>

So you are basically overwriting dict.__init__() with a no-op
Rec1.__init__(). The easiest fix is to omit the initializer:

 >>> class R(dict):
	def __call__(self, fmt): return fmt.format_map(self)


 >>> r = R({"a": 1}, b=2)
 >>> r["c"] = 3
 >>> r
{'a': 1, 'b': 2, 'c': 3}
 >>> r("{a} + {b} = {c}")
'1 + 2 = 3'




More information about the Tutor mailing list