[Python-Dev] PEP 0424: A method for exposing a length hint (original) (raw)
Mark Shannon mark at hotpy.org
Sun Jul 15 16:39:07 CEST 2012
- Previous message: [Python-Dev] PEP 0424: A method for exposing a length hint
- Next message: [Python-Dev] PEP 0424: A method for exposing a length hint
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Nick Coghlan wrote:
Right, I agree on the value in being able to return something to say "this cannot be converted to a concrete container".
I still haven't seen a use case where the appropriate response to "I don't know" differs from the appropriate response to a hint of zero - that is, you don't preallocate, you just start iterating.
There seem to be 5 possible classes values of length_hint that an iterator object can provide:
Don't implement it at all.
Implement length_hint() but don't want to return any value. Either raise an exception (TypeError) -- As suggested in the PEP. or return NotImplemented -- my preferred option.
Return a "don't know" value: Returning 0 would be fine for this, but the VM might want to respond differently to "don't know" and 0. length_hint() == 0 container should be minimum size. length_hint() == "unknown" container starts at default size.
Infinite iterator: Could return float('inf'), but given this is a "hint" then returning sys.maxsize or sys.maxsize + 1 might be OK. Alternatively raise an OverflowError
A meaningful length. No problem :)
Also, what are the allowable return types?
- int only
- Any number (ie any type with a int() method)?
- Or any integer-like object (ie a type with a index() method)?
My suggestion:
a) Don't want to return any value or "don't know": return NotImplemented b) For infinite iterators: raise an OverflowError c) All other cases: return an int or a type with a index() method.
Cheers, Mark.
- Previous message: [Python-Dev] PEP 0424: A method for exposing a length hint
- Next message: [Python-Dev] PEP 0424: A method for exposing a length hint
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]