Automatically Type Cast Parameters In Python

后端 未结 6 2041
死守一世寂寞
死守一世寂寞 2020-12-30 04:37

Background:
I mostly run python scripts from the command line in pipelines and so my arguments are always strings that need to be type casted to the app

6条回答
  •  被撕碎了的回忆
    2020-12-30 05:08

    I know I arrived late at this game, but how about eval?

    def my_cast(a):
    try:
        return eval(a)
    except:
        return a
    

    or alternatively (and more safely):

    from ast import literal_eval
    
    def mycast(a):
      try:
        return literal_eval(a)
      except:
        return a
    

提交回复
热议问题