Automatically Type Cast Parameters In Python

后端 未结 6 2129
死守一世寂寞
死守一世寂寞 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:11

    If you want to auto-convert values:

    def boolify(s):
        if s == 'True':
            return True
        if s == 'False':
            return False
        raise ValueError("huh?")
    
    def autoconvert(s):
        for fn in (boolify, int, float):
            try:
                return fn(s)
            except ValueError:
                pass
        return s
    

    You can adjust boolify to accept other boolean values if you like.

提交回复
热议问题