[英]What is the most pythonic way to pass kwargs in this function?
I want to create a shortcut function for creating a question object in my django tests. 我想在我的Django测试中创建一个用于创建问题对象的快捷功能。
I don't like to type something like new_q(timedelta(minutes=1))
all the time and I want to write that timedelta only once and be able to pass it's arguments in a nice way to the new_q
function. 我不喜欢一直输入new_q(timedelta(minutes=1))
类的东西,我只想写一次timedelta并能够以一种很好的方式将其参数传递给new_q
函数。
Is there any pythonic one line solution to this in which I don't have to capture the kwargs to a variable and then create a timedelta object in a new line? 是否有任何Pythonic的单行解决方案,其中我不必将kwargs捕获到变量中,然后在新行中创建timedelta对象?
from datetime import timedelta
from django.utils import timezone
def new_q(question_text = '', offset=timedelta(**kwargs)):
time = timezone.now() + offset
return Question.objects.create(question_text=question_text, pub_date=time)
usage: 用法:
test1 = new_q(minutes=1)
test2 = new_q('yo?', seconds=1)
test2 = new_q(question_text = 'maw?', hours=11)
test2 = new_q(question_text = 'maw?')
test2 = new_q('yo?')
def new_q(question_text = '', **kwargs):
time = timezone.now() + timedelta(**kwargs)
...
This is still pretty concise: it mentions kwargs
twice, but there's no offset
or anything else extra. 这仍然很简洁:它两次提到kwargs
,但是没有offset
或其他任何多余的东西。
What you're trying to write here doesn't quite make sense: 您要在此处编写的内容不太有意义:
def new_q(question_text = '', offset=timedelta(**kwargs)):
This creates a default value for offset
, and that value is created by calling timedelta(**kwargs)
on whatever happens to be in kwargs
at the time the function is defined. 这将为offset
创建一个默认值,并且通过在定义函数时在kwargs
中碰巧发生的任何事情调用timedelta(**kwargs)
来创建该值。 (Which is probably nothing at all, so you get a NameError
.) (这可能什么都不是,因此您会收到NameError
。)
What you want is something like this: 您想要的是这样的:
def new_q(question_text = '', offset=None, **kwargs):
if offset is None:
offset = timedelta(**kwargs)
Now you're calling timedelta
when the function is called, rather than when it's defined, and using the value of kwargs
passed into the function, rather than whatever value that variable has at function definition time. 现在,您要在调用timedelta
时(而不是在定义函数时)调用timedelta
,并使用传递给函数的kwargs
的值,而不是变量在函数定义时具有的任何值。
You could of course add some error handling, so the TypeError
you get for an unknown keyword argument mentions new_q
instead of timedelta
, and so that it's an error to specify both offset
and minutes
, and so on. 当然,您可以添加一些错误处理,因此,针对未知关键字参数获得的TypeError
提到了new_q
而不是timedelta
,因此指定offset
和minutes
都是错误的,依此类推。
Also, if someone passes neither offset
nor any other keyword arguments, this will create a timedelta()
—which is an empty timedelta
(0 seconds). 另外,如果某人既未传递offset
也未传递任何其他关键字参数,则将创建一个timedelta()
-这是一个空的timedelta
(0秒)。 Is that what you want? 那是你要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.