seq*_*eek 13 python parameters types casting
背景:
我主要从管道中的命令行运行python脚本,因此我的参数总是需要类型转换为适当类型的字符串.我每天都会编写很多小脚本,并为每个脚本输入每个参数的类型需要更多的时间.
问题:
是否有一种规范的方法可以自动为函数键入强制转换参数?
我的方式:
如果没有更好的方法,我已经开发了一个装饰器来做我想做的事情.装饰器是下面的autocast fxn.在示例中,装饰的fxn是fxn2.请注意,在代码块的末尾,我将1和2作为字符串传递,如果您运行脚本,它将自动添加它们.这是一个很好的方法吗?
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')
Run Code Online (Sandbox Code Playgroud)
编辑:对于任何来到这里并想要更新和简洁的工作版本的人,请访问:
https://github.com/sequenceGeek/cgAutoCast
这里也是基于以上的快速工作版本:
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')
Run Code Online (Sandbox Code Playgroud)
Ned*_*der 15
如果要自动转换值:
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
Run Code Online (Sandbox Code Playgroud)
boolify如果您愿意,可以调整以接受其他布尔值.
如果您信任源,则可以使用plain eval输入字符串:
>>> eval("3.2", {}, {})
3.2
>>> eval("True", {}, {})
True
Run Code Online (Sandbox Code Playgroud)
但是如果你不信任源代码,你可以使用ast模块中的literal_eval.
>>> ast.literal_eval("'hi'")
'hi'
>>> ast.literal_eval("(5, 3, ['a', 'b'])")
(5, 3, ['a', 'b'])
Run Code Online (Sandbox Code Playgroud)
编辑: 作为Ned Batchelder的评论,它不会接受非引用的字符串,所以我添加了一个解决方法,也是一个关于带有关键字参数的autocaste装饰器的示例.
import ast
def my_eval(s):
try:
return ast.literal_eval(s)
except ValueError: #maybe it's a string, eval failed, return anyway
return s #thanks gnibbler
def autocaste(func):
def wrapped(*c, **d):
cp = [my_eval(x) for x in c]
dp = {i: my_eval(j) for i,j in d.items()} #for Python 2.6+
#you can use dict((i, my_eval(j)) for i,j in d.items()) for older versions
return func(*cp, **dp)
return wrapped
@autocaste
def f(a, b):
return a + b
print(f("3.4", "1")) # 4.4
print(f("s", "sd")) # ssd
print(my_eval("True")) # True
print(my_eval("None")) # None
print(my_eval("[1, 2, (3, 4)]")) # [1, 2, (3, 4)]
Run Code Online (Sandbox Code Playgroud)
我想你可以用函数装饰器制作一个类型签名系统,就像你有的一样,只有一个带参数的。例如:
@signature(int, str, int)
func(x, y, z):
...
Run Code Online (Sandbox Code Playgroud)
这样的装饰器可以很容易地构建。像这样的东西(编辑 - 有效!):
def signature(*args, **kwargs):
def decorator(fn):
def wrapped(*fn_args, **fn_kwargs):
new_args = [t(raw) for t, raw in zip(args, fn_args)]
new_kwargs = dict([(k, kwargs[k](v)) for k, v in fn_kwargs.items()])
return fn(*new_args, **new_kwargs)
return wrapped
return decorator
Run Code Online (Sandbox Code Playgroud)
就像那样,您现在可以为函数注入类型签名!
@signature(int, int)
def foo(x, y):
print type(x)
print type(y)
print x+y
>>> foo('3','4')
<type: 'int'>
<type: 'int'>
7
Run Code Online (Sandbox Code Playgroud)
基本上,这是@utdemir 方法的类型显式版本。