Puede que tenga un problema mental aquí, pero realmente no puedo entender qué es lo que está mal con mi código:
for key in tmpDict: print type(tmpDict[key]) time.sleep(1) if(type(tmpDict[key])==list): print 'this is never visible' break
la salida es pero la instrucción if nunca se dispara. ¿Alguien puede detectar mi error aquí?
Su problema es que ha redefinido la list
como una variable anteriormente en su código. Esto significa que cuando type(tmpDict[key])==list
, devolverá False
porque no son iguales.
Dicho esto, en su lugar, debe usar isinstance(tmpDict[key], list)
al probar el tipo de algo, esto no evitará el problema de sobrescribir la list
pero es una forma más pythonica de verificar el tipo.
Debes intentar usar isinstance()
if isinstance(object, (list,)): ## DO what you want
En tu caso
if isinstance(tmpDict[key], (list,)): ## DO SOMETHING
EDITAR: Después de ver el comentario a mi respuesta, pensé en desarrollarlo.
x = [1,2,3] if type(x) == list(): print "This wont work" if type(x) == list: ## one of the way to see if it's list print "this will work" if type(x) == type(list()): print "lets see if this works" if isinstance(x,(list,)): ## most preferred way to check if it's list print "This should work just fine" if isinstance(x, list): ## Nice way to check if it's a list print "This should also work just fine"
Esto parece funcionar para mí:
>>>a = ['x', 'y', 'z'] >>>type(a) >>>isinstance(a, list) True