首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python bson库:获取bson别名

Python bson库:获取bson别名
EN

Stack Overflow用户
提问于 2017-01-31 22:17:24
回答 1查看 248关注 0票数 3

我正在寻找一个type_of方法,如下所示:

代码语言:javascript
复制
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.

我想要的结果( intstring)是BSON别名(参见https://docs.mongodb.com/manual/reference/bson-types/)。

此方法type_of是否已存在?

如果它返回类型的数字(1表示双精度,2表示字符串...),这是可以的。

谢谢,

编辑:这是我目前的解决方案:

代码语言:javascript
复制
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"
EN

回答 1

Stack Overflow用户

发布于 2017-02-11 03:49:47

如果你想要实际的BSON类型(number不是bson类型),我不确定有没有办法。我使用此函数来帮助整理python将对象编码为:

代码语言:javascript
复制
def what_bson_type(input):
    import bson
    return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]

注意:这些“类型”不符合bson规范,但它们在过去已经足够好地帮助我了。

代码语言:javascript
复制
>>> 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'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41959847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档