Estoy buscando un método type_of como se muestra a continuación:
import bson bson.type_of(42) # it should return "int". bson.type_of("hello") # it should return "string". type("hello").__name__ # it returns "str" and not "string" therefore no suitable. Los resultados que quiero ( int y string ) son el alias BSON (consulte https://docs.mongodb.com/manual/reference/bson-types/ ).
¿Este método type_of ya existe?
Está bien si devuelve los números de los tipos (1 para Doble, 2 para Cadena...).
Gracias,
Editar: Aquí está la solución que tengo por el momento:
type_of = { type(2.5).__name__: "number", type(1).__name__: "number", type("a_string").__name__: "string", type([1, 2]).__name__: "array", type(True).__name__: "bool" } # type_of[type(3).__name__] returns "number"Si desea los tipos BSON reales (el número no es un tipo bson), no estoy seguro de que haya una manera. He usado esta función para ayudar a determinar qué python codificará el objeto como:
def what_bson_type(input): import bson return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]Nota: estos "tipos" no coinciden con las especificaciones de bson, pero han sido lo suficientemente buenos para ayudarme en el pasado.
>>> what_bson_type("hi") 'string' >>> what_bson_type(1) 'int' >>> what_bson_type(sys.maxint) 'int64' >>> what_bson_type(True) 'boolean' >>> what_bson_type({"a":"b"}) 'object' >>> what_bson_type(1.2) 'float' >>> what_bson_type([1,2]) 'array' >>> what_bson_type(re.compile(r".*")) 'regex' >>> what_bson_type(bson.Binary("hi")) 'binary'