News for hackers. Stuff that matters.
Re:Python built-ins worth learning (2019) by mturmon on Thursday March 17, 2022 @01:46PM (#30713908)
Alas, I find this suggestion unpersuasive for the use I have in mind. I get that there would be cases it does apply to.

I just want to enforce that the object acts like a list, mainly versus a float, int, or boolean. Tuples are definitely 100% ok, and if someone wants to give me a set, that's almost certainly OK too, in the use cases I'm considering. And so is a numpy vector!

Often these objects are held in a container (a dict or class variable), so type annotations would be clumsy as far as I know. Wouldn't I need to create a separate object to enforce the annotation?

And the type annotation would need to allow tuples and all flavors of lists or numpy arrays.

On the other end of the scale, I don't think either of us wants to use isinstance checks!

My primary intent isn't to be bulletproof, it's to show intent. The main fail of using len() in this way is that it accepts strings.

Re:Python built-ins worth learning (2019) by saila on Monday March 21, 2022 @09:00PM (#30761687)
I don't see how using len() this way is any different than doing an isinstance check. You're essentially saying, "If this object doesn't respond to len(), raise a TypeError."
Re:Python built-ins worth learning (2019) by dragonwriter on Thursday March 24, 2022 @02:07AM (#30786773)
> I don't see how using len() this way is any different than doing an isinstance check.

It's a protocol (structural) runtime type check, not a class (nominal) runtime type check.

Re:Python built-ins worth learning (2019) by saila on Wednesday March 30, 2022 @12:43AM (#30851555)
Perhaps true but misses the point. If you’re using len() for type checking, it’s essentially no different than doing isinstance(items, Sized). The latter explicitly calls out what you’re doing and makes it clear, to me, that’s it’s not really correct, in that it doesn’t show your intent, which is to enforce a sequence of items in a container not that the object has a size.
Re:Python built-ins worth learning (2019) by mturmon on Thursday March 24, 2022 @01:54AM (#30786729)
Tuple, list, and numpy array are all different isinstance()’s, so I’d have to call them all out. len() avoids that.
Re:Python built-ins worth learning (2019) by saila on Wednesday March 30, 2022 @12:39AM (#30851537)
This is incorrect, because you can generally do this for sequence types:

    isinstance(items, Sequence)
Or perhaps:

    isinstance(items, Iterable)  # works with numpy arrays
Or, equivalent to using len() for type checking, you could do:

    isinstance(items, Sized)