Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Hint for finite iterable

My function foo accepts an argument things which is turned into a list internally.

def foo(things):
    things = list(things)
    # more code

The list constructor accepts any iterable.

However, annotating things with typing.Iterable does not give the user a clue that the iterable must be finite, not something like itertools.count().

What's the correct type hint to use in this case?

like image 927
actual_panda Avatar asked Apr 11 '20 10:04

actual_panda


People also ask

What is iterable in typing?

Iterable is a pseudo-type introduced in PHP 7.1. It accepts any array or object implementing the Traversable interface. Both of these types are iterable using foreach and can be used with yield from within a generator.

How do you type hinting in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

How do you use type hint?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5. The name: str syntax indicates the name argument should be of type str . The -> syntax indicates the greet() function will return a string.

Does Python 3.6 support type hints?

You can add type hints to function/method parameters and return types (Python 3.5), and variables used in assignment (effectively declarations – Python 3.6).


1 Answers

I am not aware of any possible way to achieve this in Python as you cannot provide such constraints in type hints.


However, probably the Collection type might be useful in your context as a workaround:

class collections.abc.Collection

ABC for sized iterable container classes.

This requires objects to have a __len__, which is a more strict requirement than being finite. For example, finite generators don't count as Collection.

like image 135
Giorgos Myrianthous Avatar answered Nov 07 '22 06:11

Giorgos Myrianthous