Skip to content

Ottenere e verificare il tipo di un oggetto in Python: type(), isinstance()

Python

In Python, puoi ottenere, stampare e controllare il tipo di un oggetto (variabile e letterale) con le funzioni integrate type() e isinstance().

In questo articolo vengono descritti i seguenti contenuti.

  • Ottieni e stampa il tipo di un oggetto:type()
  • Verifica il tipo di un oggetto:type(), isinstance()
    • Con tipo()
    • Con istanza()
    • La differenza tra tipo() e istanza()


Ottieni e stampa il tipo di un oggetto:type()

type() fornisce il tipo di un oggetto. Puoi usare per ottenere e stampare il tipo di una variabile e un letterale come typeof in altri linguaggi di programmazione.

print(type('string'))
# <class 'str'>

print(type(100))
# <class 'int'>

print(type([0, 1, 2]))
# <class 'list'>

Il valore restituito di type() è un oggetto di tipo come str o int.

print(type(type('string')))
# <class 'type'>

print(type(str))
# <class 'type'>

Verifica il tipo di un oggetto:type(), isinstance()

Usa type() o isinstance() per verificare se un oggetto è di un tipo specifico.

Con tipo()

Confrontando il valore restituito di tipo() con qualsiasi tipo, puoi verificare se l’oggetto è di quel tipo.

print(type('string') is str)
# True

print(type('string') is int)
# False
def is_str(v):
    return type(v) is str

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False

Se vuoi verificare se è uno di diversi tipi, usa in e più tipi di tuple.

def is_str_or_int(v):
    return type(v) in (str, int)

print(is_str_or_int('string'))
# True

print(is_str_or_int(100))
# True

print(is_str_or_int([0, 1, 2]))
# False

È inoltre possibile definire funzioni che modificano le operazioni a seconda del tipo.

def type_condition(v):
    if type(v) is str:
        print('type is str')
    elif type(v) is int:
        print('type is int')
    else:
        print('type is not str or int')

type_condition('string')
# type is str

type_condition(100)
# type is int

type_condition([0, 1, 2])
# type is not str or int

Con istanza()

isinstance(oggetto, tipo) produce True se il primo oggetto argomento è un’istanza del secondo tipo di argomento o un’istanza di una sottoclasse di tipo.

Puoi usare una tupla come secondo argomento. Restituisce True se è un’istanza di qualsiasi tipo.

print(isinstance('string', str))
# True

print(isinstance(100, str))
# False

print(isinstance(100, (int, str)))
# True

Funzioni simili agli esempi precedenti che utilizzano type() possono essere scritte come segue:

def is_str(v):
    return isinstance(v, str)

print(is_str('string'))
# True

print(is_str(100))
# False

print(is_str([0, 1, 2]))
# False
def is_str_or_int(v):
    return isinstance(v, (int, str))

print(is_str_or_int('string'))
# True

print(is_str_or_int(100))
# True

print(is_str_or_int([0, 1, 2]))
# False
def type_condition(v):
    if isinstance(v, str):
        print('type is str')
    elif isinstance(v, int):
        print('type is int')
    else:
        print('type is not str or int')

type_condition('string')
# type is str

type_condition(100)
# type is int

type_condition([0, 1, 2])
# type is not str or int

La differenza tra tipo() e istanza()

La differenza tra type() e isinstance() è che isinstance() restituisce True anche per istanze di sottoclassi che ereditano la classe specificata nel secondo argomento.

Ad esempio, definire la seguente superclasse (classe base) e sottoclasse (classe derivata).

class Base:
    pass

class Derive(Base):
    pass

base = Base()
print(type(base))
# <class '__main__.Base'>

derive = Derive()
print(type(derive))
# <class '__main__.Derive'>

type() restituisce True solo quando i tipi composti, ma isinstance() restituisce True anche per la superclasse.

print(type(derive) is Derive)
# True

print(type(derive) is Base)
# False

print(isinstance(derive, Derive))
# True

print(isinstance(derive, Base))
# True

Ad esempio, il tipo booleano bool (Vero, Falso) è una sottoclasse di int. isinstance() restituisce True sia per int che per bool per un oggetto di bool.

print(type(True))
# <class 'bool'>

print(type(True) is bool)
# True

print(type(True) is int)
# False

print(isinstance(True, bool))
# True

print(isinstance(True, int))
# True

Usa type() se vuoi controllare il tipo esatto e isinstance() se vuoi controllare l’ereditarietà.

Una funzione incorporata issubclass() controlla se una classe è una sottoclasse di un’altra classe.

print(issubclass(bool, int))
# True

print(issubclass(bool, float))
# False