Python standardizes T → str via __str__, but it does not for the partial inverse str ⇀ T. Given a type and a string, nothing in the standard enables introspection whether the type offers string parsing or how to invoke it. A few constructors oblige, but not all of them are useful, like bool("False") yields True.
I have drafted a PEP proposing an optional class method, __parse__(cls, text: str, /) -> Self, whose presence is the introspectable, overloadable declaration. It requires no changes to syntax, constructors, or serialization formats. The target type is a parameter, so the problems that stopped __json__/__deserialize__ should not arise.
Before pursuing a sponsor, is the problem already recognized in discussions that I can’t find? And do the proposal’s two open questions – dunder versus plain class method, and the strength of the round-trip requirement – have obvious answers I’m not seeing?
It is not entirely clear how this would get called, and how this would be any different (from a consumer’s experience) to a constructor that just receives a string
Yes, I should have been more explicit upfront. It’s called directly by whoever holds the type with T.__parse__(s). Nothing in the interpreter invokes it, consumer only. Given T, nothing tells you whether T(s) correctly parses s:
python
bool("False") # wrong value
list("[1, 2]") # unexpected result
datetime("2026-10-16") # fails, must know fromisoformat() exists
Right. Going from str(x) through __parse__ and back to a type is serialization in the narrow sense. The non-goal is being universal at it by prescribing one encoding for all types, with the type recovered from the data. __parse__ standardizes only the interface and every type keeps its own grammar. The bullet should say “no common format”. I will fix that.
Why does it need to be a dunder specified by the language spec if the language doesn’t ever use it and it’s used like a normal function (albeit with the ‘why is this a dunder’ question)?
Preserving the existing behaviour is exactly why a separate, declared method is proposed. bool("False") remains True, but it gains bool.__parse__("False") == False.
parse as a plain class method is exactly “Open Issue 1” and that would be fine as well. The specification would remain unchanged under the renaming.
format already names the forward direction, value → string, and takes a spec. The proposed method is the reverse direction and takes no spec, since each type defines its own grammar. It is the counterpart of str.
Why does it need to be a dunder specified by the language spec if the language doesn’t ever use it and it’s used like a normal function (albeit with the ‘why is this a dunder’ question)?
That’s “Open Issue 1”, and it really doesn’t have to be a dunder. There is precedent, though. The data model already has dunders nothing in the interpreter calls:
__fspath__ (only os.fspath())
__length_hint__ (only operator.length_hint())
__sizeof__ (only sys.getsizeof())
So a dunder reserves a name and fixes its contract. It does not require implicit dispatch.
What the reservation would buy: T.parse may already exist with any meaning, so finding it tells a consumer nothing. Finding T.__parse__ tells it the contract holds, because nothing else may use that name. That guarantee is the proposal.
Whether it is worth the dunder is what I hope to settle here.
I’d go even further than that and ask why it even needs to be a method at all. Why can’t it be a standalone function, extensible via functools.singledispatch?
That could be developed as a 3rd party library, and proposed for the stdlib if/when it becomes sufficiently stable and popular to make such a move appropriate.
One snag with singledispatch: it dispatches on type(arg) and the argument here is a class, so every T lands on type. It would require a registry keyed by the class instead, and a registry lives with a function, not with the type. A type in library A then has to import library B to register, which is the per-consumer complexity I’m trying to avoid. A method puts the declaration on the type itself, where every consumer can find it.
A third-party package for the consumer side, with shims for the stdlib types, is the right next step either way. I’ll work on it and report back.
Aside from party tricks with the word “False”, the bool contructor is very useful and consistent. It follows the same rules as truthiness uses anywhere else: anything that’s empty becomes False and anything that isn’t empty becomes True. Since a string with five charactes in it is not empty, it is True. Maybe that’s not the rules you want to use, but those are the rules that truthiness follows in Python. (This is the case in MOST programming languages. The rules for truthiness differ from language to language, but they’re usually quite simple. In fact, the only one I can think of with a bizarre exception like you’re suggesting here is PHP.)
but it’s by no means mandatory. So there isn’t even a standard __repr__ → object. If someone adhere to the convention, __parse__ is not need at all, eval is sufficient
__str__ is an human-readable representation of the object, so it’s not at all suitablefor a deserialization. Since you mentioned datetime in your PEP, this is a little example:
$ ./python
Python 3.15.0 (tags/v3.15.0-dirty:d220409a13b, Oct 10 2026, 04:51:10) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> now = datetime.datetime.now()
>>> r = repr(now)
>>> s = str(now)
>>> r
'datetime.datetime(2026, 10, 17, 2, 46, 15, 944391)'
>>> eval(r)
datetime.datetime(2026, 10, 17, 2, 46, 15, 944391)
>>> s
'2026-10-17 02:46:15.944391'
>>> eval(s)
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
eval(s)
~~~~^^^
File "<string>", line 1
2026-10-17 02:46:15.944391
^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
>>>
Perhaps you’d like to propose a
parse(val: str) -> Any
as an eval specialized in deserializing an object’s __repr__ that’s not unsafe. But you put it in “Rejected Ideas”
That should be fixed if we introduce multiple signatures for callables. For example, documentations for current constructors of int/float/complex have special cases for string input:
class int(string, /, base=10):
pass
class float(string, /):
pass
class complex(string, /):
pass
Unfortunately, the inspect module (and friends) don’t understand this.
Why it would be helpful for someone? It’s actually quite common that string parsing in the constructor altered by some options. For int - it’s base, for Decimal - it’s context. Shouldn’t you dunder method support also keyword arguments for options?
You said that for Decimal - __parse__ should be delegated to the constructor. How? Parsing actually depends on context argument or even on the current context. For example:
>>> decimal.Decimal('Spam')
Traceback (most recent call last):
File "<python-input-17>", line 1, in <module>
decimal.Decimal('Spam')
~~~~~~~~~~~~~~~^^^^^^^^
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
>>> isinstance(decimal.InvalidOperation, ValueError) # BTW, it's not a TypeError
False
>>> ctx1 = decimal.Context(traps=[])
>>> decimal.Decimal('Spam', ctx1)
Decimal('NaN')
>>> decimal.Decimal('Spam') # no context option, as before
Traceback (most recent call last):
File "<python-input-23>", line 1, in <module>
decimal.Decimal('Spam')
~~~~~~~~~~~~~~~^^^^^^^^
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
>>> decimal.getcontext().clear_traps() # now change the current context
>>> decimal.Decimal('Spam')
Decimal('NaN')
For a type defining both methods, type(x).__parse__(str(x)) == x SHOULD hold whenever str(x) determines x up to ==.
-1 from me, even if I have many of this kind of @classmethod parse(cls, s: str, /) in my project. I don’t think dunders are explicity enough for marking this kind of tight semantic coupling.
These two problems are related. Most __str__ representations in the wild are for human consumption and are not routinely round-trippabable. __repr__ and eval() are ideally round-trippable in the simplest cases but they are still at the end of the day just debugging aid.
Stable roundtripping parse(str(x)) == x may look trivial, but is actually a set of very strict semantic contracts that should be explicitly declared (and tested), and shouldn’t be assumed by the mere presence of a dunder. I use a nominal ABC for this purpose in my project; I design structured classes that roundtrip via __str__ and parse(cls, s: str, /) and I model them after standard specifications (such as ISO 8601 extensions for datetimes and RFCs for internet-related stuff). And that means I have to pick[1] a standard on which I give up on any freedom in customizing __str__behavior in exchange for its stability.
What I find is that parse methods generally don’t inherit too well. In my project I have classes whose constructor and parse method return specialized subclasses based on input (their standards require domain-specific collation rules), and designing them requires a lot of care. In my project I don’t need my classses to be freely subclassable (many are final or considered sealed), but this limitation just won’t be acceptable for most built-in and stdlib classes which are widely subclassed.
With the progress in and adoption of free-threading, I think we’re well past the point of introducing more mutable globals that can be mutated everywhere into the ecosystem.
And dependency injection as well. There are sensible defaults though in most cases.
Python 3.14.7 (tags/v3.14.7:823f0323ee6, Aug 12 2026, 13:12:17) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gmpy2 import *
>>> mpz('0x123')
mpz(291)
>>> int('0x123')
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
int('0x123')
~~~^^^^^^^^^
ValueError: invalid literal for int() with base 10: '0x123'
I would like to take one step back, because the discussion has drifted to machine-readable round trips, and it’s precisely where the proposal tries not to go. Instead it is all about getting the human into the loop. str() and __str__ make it human readable, and .parse() or __parse__ try to read back what the human wrote.
Perhaps I should share where the proposal is coming from: an extension for Fire that uses type hints for argument parsing. The user types --timeout 2.5 --since 2026-10-16 --addr 192.168.1.1 --verbose False on a command line, and every argument is of the form the target type’s __str__ produces. Fire can know all the type hints, but it does not have a standard way to __parse__ those strings back into the expected data types that works for float, date, IPv4Address, bool and custom classes alike. It must recognize each type, implement parsers or shim compatible contstructors or class methods, and maintain each one of them.
If the language’s standard of translating a data type into a human-readable form were to be symmetrically augmented by a reverse standard for attempting to turn well-formed human input back into the data type, it would naturally evolve input capability over time in the places where it belongs: next to the __str__ that defines the output format. At the moment, Python relies on individual developers solving the string parsing problem over and over again.