Automatically Type Cast Parameters In Python

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

    There are couple of problems in your snippet.

    #first test bools
    if var == 'True':
            return True
    elif var == 'False':
            return False
    

    This would always check for True because you are testing against the strings 'True' and 'False'.

    There is not an automatic coercion of types in python. Your arguments when you receive via *args and **kwargs can be anything. First will look for list of values (each of which can be any datatype, primitive and complex) and second will look for a mapping (with any valid mapping possible). So if you write a decorator, you will end up with a good list of error checks.

    Normally, if you wish to send in str, just when the function is invoked, typecast it to string via (str) and send it.

提交回复
热议问题