On Fri, 1 Sept 2023 at 06:39, Chris Green via Python-list
There's no clear answer to this, because you aren't really
constructing a Person here. So there are a few options that seem
pretty reasonable:
1) As you say, raise ValueError. The problem is the value passed in
(it's the right type, but the value wasn't found), so, ValueError.
2) KeyError. This emphasizes the fact that you're effectively looking
up in a mapping. Quite odd for a constructor though.
3) A custom RecordNotFound exception. You're doing something unusual,
so make it your own exception.
TBH I would suggest making a slightly different API:
person.Person.from_name('Fred')
ie a classmethod alternate constructor. These can most definitely
raise ValueError when the value given isn't appropriate:
>>> datetime.datetime.fromordinal(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: ordinal must be >= 1
and it makes good sense for a method like this to be doing lookups,
rather than construction per se. (At a technical level, it's
presumably constructing new objects.)
To help with making that decision, what happens if you construct two
Person objects for the same actual person? Would you return the same
object (ie maintain a cache and deduplicate)? Or does each one take a
snapshot of the data at the instant of construction, and thus you can
observe changes through time by constructing more? Both are reasonable
and make sense, but they lend themselves to slightly different
approaches.
ChrisA