On Thu, May 7, 2020 at 11:16 AM David Mertz <mertz@gnosis.cx> wrote:
On Wed, May 6, 2020 at 8:37 PM Chris Angelico <rosuav@gmail.com> wrote:
The only precedent that jumps out for me is itertools.chain() and itertools.chain.from_iterable(). It's quite likely that something I don't use much has used the same pattern though.
That's an example of a very common pattern of alternate constructors.
The other Chris' comment was:
zip.shortest(...) # same as zip(...) / zip.longest(...) / zip.checksame(...) I kind of like this -- is there any precedent for it in the standard library?
If it's a very common pattern, do you know of any in the standard library beyond the one I mentioned? Not about bikeshedding the spelling of the different constructors, but just:
1. A callable; 2. That has one or more functions attached to perform some variation on what that callable itself does.
The first one that comes to mind is the datetime types, which have from* methods that construct them from timestamps, strings, etc. A quick search of the cpython/Lib directory shows Decimal.from_float, dict.fromkeys, socket.fromfd, and a bunch of others, all of the basic form "construct one of these things in a slightly different way". On Thu, May 7, 2020 at 11:19 AM Eric V. Smith <eric@trueblade.com> wrote:
I think David is right: itertools.chain.from_iterable() is the only place I know of with an attribute on a function that's another function. Alternate constructors are generally classmethods. Not that the distinction is terribly important, but it is a distinction, and it's documented differently.
What do you mean? Are you saying that itertools.chain is a function but datetime.datetime is a class, and that this is fundamentally different? Because Python disagrees:
import itertools, datetime type(itertools.chain), type(datetime.datetime) (<class 'type'>, <class 'type'>)
itertools.chain.from_iterable is a classmethod (albeit implemented in C, in current CPython). ChrisA