x = "casa"
type(x)
str
x = "a" + 5
x = "a" + 5
x
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-2-b25c2ff693f6> in <module> ----> 1 x = "a" + 5 2 x TypeError: can only concatenate str (not "int") to str
opcion = input("ingresa 1 para verificar y 2 para no")
if opcion == "1":
print("Estoy chequeando...")
print("e" + 4 )
else:
print("Ahora no estoy dando error")
ingresa 1 para verificar y 2 para no1 Estoy chequeando...
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-17-953bb85b289f> in <module> 2 if opcion == "1": 3 print("Estoy chequeando...") ----> 4 print("e" + 4 ) 5 else: 6 print("Ahora no estoy dando error") TypeError: can only concatenate str (not "int") to str
def headline(text, align=True):
if align:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "-")
print(headline("python type checking"))
Python Type Checking --------------------
print(headline("python type checking", align=False))
-------------- Python Type Checking --------------
print(headline("python type checking", align="left"))
Python Type Checking --------------------
def headline(text: str, align: bool = True) -> str:
if align:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "-")
print(headline("python type checking", align="left"))
Python Type Checking --------------------
Si bien estas anotaciones están disponibles en tiempo de ejecución a través del atributo __annotations__, no se realiza ninguna verificación de tipo en tiempo de ejecución.
headline.__annotations__
{'text': str, 'align': bool, 'return': str}
def headline(text: str, centered: bool = True) -> str:
if centered:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "-")
print(headline("python type checking"))
print(headline("use mypy", centered=True))
Python Type Checking -------------------- Use Mypy --------
def funcion(arg1: arg_type, arg2: arg_type = valor) -> return_type:
...
import math
def area_circunferencia(radio: float) -> float:
return math.pi * radio ** 2
area = area_circunferencia(2)
print(area)
12.566370614359172
pi: float = 3.1415
def area_circunferencia(radio: float) -> float:
return math.pi * radio ** 2
area = area_circunferencia(2)
print(area)
12.566370614359172
area_circunferencia.__annotations__
{'radio': float, 'return': float}
__annotations__
{'pi': float, 'mensaje': str, 'nombre_bandas': list, 'notas': tuple, 'opciones': dict}
mensaje: str
__annotations__
{'pi': float, 'mensaje': str, 'nombre_bandas': list, 'notas': tuple, 'opciones': dict}
mensaje = 10
mensaje
10
nombre_bandas: list = ["Led Zeppelin", "AC/DC", "Queen"]
notas: tuple = (7, 8, 9, 10)
opciones: dict = {"centered": False, "capitalize": True}
from typing import Dict, List, Tuple
nombre_bandas: List[str] = ["Led Zeppelin", "AC/DC", "Queen"]
notas: Tuple[int, int, int, int] = (7, 8, 9, 10)
opciones: Dict[str, bool] = {"centered": False, "capitalize": True}
from typing import List, Sequence
def cuadrados(elems: Sequence[float]) -> List[float]:
return [x**2 for x in elems]
cuadrados([1, 2, 3])
[1, 4, 9]
import random
def elijo_al_azar(lista_de_elementos):
return random.choice(lista_de_elementos)
lista = [1, "dos", 3.1415]
elijo_al_azar(lista)
1
import random
from typing import Any, Sequence
def elijo_al_azar(lista_de_elementos: Sequence[Any]) -> Any:
return random.choice(lista_de_elementos)
lista = [1, "dos", 3.1415]
elijo_al_azar(lista)
1
class Jugador:
def __init__(self,
nombre: str,
juego: str = "Tetris",
tiene_equipo: bool = False,
equipo: str = None) -> None:
self.nombre = nombre
self.juego = juego
self.tiene_equipo = tiene_equipo
self.equipo = equipo
def jugar(self) -> None:
if self.tiene_equipo:
print (f"{self.nombre} juega en el equipo {self.equipo} al {self.juego}")
else:
print(f"{self.nombre} juega solo al {self.juego}")
class SuperHeroe():
""" Esta clase define a un superheroe
villanos: representa a los enemigos de todos los superhéroes
"""
villanos: List[str] = []
def __init__(self, nombre: str, alias: str) -> None:
self._nombre = nombre
self._enemigos = []
La PEP 526: tiene como objetivo mostrar de qué manera se pueden realizar anotación de varoables (incluidas las variables de clase y las variables de instancia),
Artículo de RealPython: https://realpython.com/python-type-checking/