我正在寻找一个type_of方法,如下所示:
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.我想要的结果( int和string)是BSON别名(参见https://docs.mongodb.com/manual/reference/bson-types/)。
此方法type_of是否已存在?
如果它返回类型的数字(1表示双精度,2表示字符串...),这是可以的。
谢谢,
编辑:这是我目前的解决方案:
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"发布于 2017-02-11 03:49:47
如果你想要实际的BSON类型(number不是bson类型),我不确定有没有办法。我使用此函数来帮助整理python将对象编码为:
def what_bson_type(input):
import bson
return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]注意:这些“类型”不符合bson规范,但它们在过去已经足够好地帮助我了。
>>> 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'https://stackoverflow.com/questions/41959847
复制相似问题