Reputation: 3694
(Maybe b/c I'm from a C++ world) I want to verify some python variable is
list(string)
or list(dict(int, string))
or SomethingIterable(string)
Is there a simple and unified way to do it? (Instead of writing customized code to iterate and verify each instance..)
I emphasize that I understand in Python list
can have elements of different types, which is exactly the reason why I ask how to verify a list
which are composed by just a certain type e.g. string
.
Upvotes: 2
Views: 493
Reputation: 49330
It seems that you are looking for an array (array.array
), not a list:
>>> l = [1]
>>> l.append('a')
>>> import array
>>> a = array.array('l')
>>> a.append(3)
>>> a.append('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)
>>> a
array('l', [3])
As you get more and more comfortable with Python, though, you will gradually learn how to structure your code in such a way that type-checking becomes unnecessary. Personally, I've never had to use an array.array
in Python (except in cases like this, where I'm specifically working with that module).
Upvotes: 1
Reputation: 39406
Use the typing module
Typically:
from typing import List
def method(value: List[str]):
pass
Upvotes: -3
Reputation: 348
In Python lists can be composed of mixed types, there is no way to do something like setting the "type" of a list. Also, even if you could, this "type" is not enforced and could change at any time.
Upvotes: 4