Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

365
Visualizações
Python bson library : get bson alias

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"
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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'
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda