Is there a standalone Python type conversion library?

后端 未结 3 1002
春和景丽
春和景丽 2021-01-27 08:49

Are there any standalone type conversion libraries?

I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be conve

3条回答
  •  礼貌的吻别
    2021-01-27 09:25

    Consider this.

    import datetime
    
    def toDate( someString ):
        return datetime.datetime.strptime( someString, "%x" ).date()
    
    typeConversionMapping = { 'integer': int, 'string': str, 'float': float, 'date': toDate }
    def typeConversionFunction( typeConversionTuple ):
        theStringRepresentation, theTypeName = typeConversionTuple
        return typeConversionMapping[theTypeName](theStringRepresentation)
    

    Is that a good enough standalone library for such a common activity? Would that be enough of a well-tested, error-resilient library? Or is there something more that's required?

    If you need more or different date/time conversions, you simply add new toDate functions with different formats.

提交回复
热议问题