[Python-ideas] More alternate constructors for builtin type
Steven D'Aprano
steve at pearwood.info
Mon May 6 20:22:59 EDT 2019
On Tue, May 07, 2019 at 09:54:03AM +1000, Cameron Simpson wrote:
> On 06May2019 18:47, Antoine Pitrou <solipsis at pitrou.net> wrote:
[...]
> >The main constructors for built-in types are used so pervasively that
> >there is no hope of actually removing such deprecated behavior.
>
> I don't find that compelling. I for one would welcome a small suite of
> unambiguous factories that can't be misused. bytes() can easily be
> misused by accident, introducing bugs and requiring debug work. I'd be
> very happy for my own future code to be able to take advantage of hard
> to misuse constructors.
There is a difference between *adding* new constructor methods, and what
Antoine is saying: that we cannot realistically remove existing uses of
the current constructors.
I think that Antoine is right: short of another major 2to3 backwards-
incompatible version, the benefit of actually removing any of the
built-in constructor behaviours is too small and the cost is too great.
So I think removal of existing behaviour should be off the table.
Or at least, taken on a case-by-case basis. Propose a specific API you
want to remove, and we'll discuss that specific API.
As for adding *new* constructors:
> Of course we could all write tiny factories for these modes but (a) we'd
> all have to write and debug them and (b) they'de all have different
> spellings and signatures
Probably because everyone will want them to do something different.
We've already seen two different semantics for the same desired
constructor call:
bytes(10) -> b'10' # like str(), but returning bytes
bytes(10) -> b'\x0A' # like ord(), but returning a byte
That suggests a possible pair of constructors:
bytes.from_int(n) -> equivalent to b'%d' % n
bytes.ord(n) -> equivalent to bytes((n,))
The proposal in this thread seems to me to be a blanket call to add new
constructors everywhere, and I don't think that's appropriate. I think
that each proposed new constructor should live or die on its own merits.
The two above for bytes seem like simple, obvious APIs that do something
useful which is otherwise a small pain point. Both are syntactic sugar
for something otherwise ugly or hard to discover.
I think that, if somebody is willing to do the work (it can't be me,
sorry) adding two new class methods to bytes for the above two cases
would be a nett win, and they should be minor enough that it doesn't
need a PEP.
Thoughts?
--
Steven
More information about the Python-ideas
mailing list