在Python中自动键入Cast参数 [英] Automatically Type Cast Parameters In Python

查看:469
本文介绍了在Python中自动键入Cast参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我大多从命令行运行python脚本在管道中,所以我的参数总是字符串,需要类型转换为适当的类型。我每天都做了很多小的脚本,类型转换每个脚本的每个参数花费的时间比它应该多。

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 appropriate type. I make a lot of little scripts each day and type casting each parameter for every script takes more time than it should.

问题:

是否有规范的方法自动为函数键入转换参数?

Question:
Is there a canonical way to automatically type cast parameters for a function?

我的方式:

我开发了一个装饰器来做我想要的,如果没有更好的方法。装饰器是下面的autocast fxn。在示例中,装饰的fxn是fxn2。注意,在代码块的结尾我传递1和2作为字符串,如果你运行脚本,它会自动添加它们。这是一个很好的方法吗?

My Way:
I've developed a decorator to do what I want if there isn't a better way. The decorator is the autocast fxn below. The decorated fxn is fxn2 in the example. Note that at the end of the code block I passed 1 and 2 as strings and if you run the script it will automatically add them. Is this a good way to do this?

def estimateType(var):
    #first test bools
    if var == 'True':
            return True
    elif var == 'False':
            return False
    else:
            #int
            try:
                    return int(var)
            except ValueError:
                    pass
            #float
            try:
                    return float(var)
            except ValueError:
                    pass
            #string
            try:
                    return str(var)
            except ValueError:
                    raise NameError('Something Messed Up Autocasting var %s (%s)' 
                                      % (var, type(var)))

def autocast(dFxn):
    '''Still need to figure out if you pass a variable with kw args!!!
    I guess I can just pass the dictionary to the fxn **args?'''
    def wrapped(*c, **d):
            print c, d
            t = [estimateType(x) for x in c]
            return dFxn(*t)
    return wrapped

@autocast
def fxn2(one, two):

   print one + two 

fxn2('1', '2')      






编辑:对于来到这里并希望更新和简洁的工作版本的任何人:

https://github.com/sequenceGeek/cgAutoCast

这里也是基于上面的快速工作版本:

And here is also quick working version based on above:

def boolify(s):
    if s == 'True' or s == 'true':
            return True
    if s == 'False' or s == 'false':
            return False
    raise ValueError('Not Boolean Value!')

def estimateType(var):
    '''guesses the str representation of the variables type'''
    var = str(var) #important if the parameters aren't strings...
    for caster in (boolify, int, float):
            try:
                    return caster(var)
            except ValueError:
                    pass
    return var

def autocast(dFxn):
    def wrapped(*c, **d):
            cp = [estimateType(x) for x in c]
            dp = dict( (i, estimateType(j)) for (i,j) in d.items())
            return dFxn(*cp, **dp)

    return wrapped

######usage######
@autocast
def randomFunction(firstVar, secondVar):
    print firstVar + secondVar

randomFunction('1', '2')


推荐答案

如果您要自动转换值:

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

您可以调整 boolify 以接受其他布尔值。

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

这篇关于在Python中自动键入Cast参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆