Nan Hua
Nan Hua

Reputation: 3694

How to do type verification in python?

(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

Answers (3)

TigerhawkT3
TigerhawkT3

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

njzk2
njzk2

Reputation: 39406

Use the typing module

Typically:

from typing import List

def method(value: List[str]):
    pass

Upvotes: -3

jmercouris
jmercouris

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

Related Questions