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?
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.
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.
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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With