I am looking for a type_of method as below :
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.
The results I want ( int and string) are the BSON alias (see https://docs.mongodb.com/manual/reference/bson-types/).
Does this method type_of already exist ?
It is okay if it returns the types' numbers ( 1 for Double, 2 for String ...).
Thank you,
Edit : Here is the solution I have for the moment:
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"
If you want the actual BSON types (number is not a bson type) I'm not sure there is a way. I've used this function to help sort out what python will encode the object as:
def what_bson_type(input):
import bson
return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]
Note: these "types" do not match the bson spec, but they have been good enough to help me in the past.
>>> 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'