Works for me:
>>> d = {"a":42}
{'a': 42}
>>> print(f"{d} is {d}")
{'a': 42} is {'a': 42}
>>> {'a': 42} is {'a': 42}
False
>>> eval(f"{d} is {d}")
False
This works just fine with dicts.
However, calling str.__dict__
returns something completely different than you'd probably expect:
>>> str.__dict__
mappingproxy({
'__new__': <built-in method __new__ of type object at 0x00007FFC55D1AC60>,
'__repr__': <slot wrapper '__repr__' of 'str' objects>,
--- snip for readability ---
This "dict-representation" is actually a MappingProxy
as you can verify with type(str.__dict__)
and cannot exactly be re-interpreted by eval()
as <built-in method __new__...
is obviously a syntax error, when used without quotes. You can easily verify this by pasting this into a Python interpreter:
>>> {"myKey": <built-in method __new__ of type object at 0x00007FFC55D1AC60>}
File "<stdin>", line 1
{"myKey": <built-in method __new__ of type object at 0x00007FFC55D1AC60>}
^
SyntaxError: invalid syntax
What you're trying to do requires not only type
(whatever this might be at runtime) to have a dict-representation, but also every member to have one - recursively! This is hard to assume in a general case.
I'm convinced what you're trying to achieve can be done using a different way - if you want elaborate your task at hand, there might be a more suitable way.
If you insist on the eval()
way, take a look at repr()
and eval()
, as generally, repr
tries to produce a string, which can be fed into eval
to produce the very same object again.
However, this is possible only, if the object implements repr
to do exactly that - which is not guaranteed. There might be objects which cannot be serialized that way.
myDict = {"myKey": "myVal"}
myDict == eval(repr(myDict))
# Output: True