sorry for the stupid noob question - kwarg?

1 view
Skip to first unread message

David Robinson

unread,
Jun 4, 2006, 11:15:57 PM6/4/06
to django-users
Really, I've tried looking this one up myself (you wouldn't believe how
many questions I *haven't* had to ask... (thanks for well-written docs
everyone)). It seems almost obvious, but I am proving to be just dense
enough to not get what is this "kwarg".

Dave

Don Arbow

unread,
Jun 4, 2006, 11:28:41 PM6/4/06
to django...@googlegroups.com
Check any python reference, it stands for keyword arguments.

Don


James Bennett

unread,
Jun 5, 2006, 1:58:52 AM6/5/06
to django...@googlegroups.com

It's a shorthand for 'keyword argument'.

Minor OT explanation, since it's a useful Python concept:

Arguments to a function can be either positional (where the function
figures out which argument is which based on the order they come in),
or keyword (where they're pass as name/value pairs, like
"Poll.objects.get(pk=1)" -- "pk=1" is a keyword argument).

Python provides shortcuts for passing lots of these, and you'll see
them used all over the place in Django. For example, you could do

my_func('foo', 'bar', 'baz')

and 'foo', 'bar' and 'baz' would be positional arguments. But you can
also build up a list, and pass it directly to a function, like so:

my_args = ['foo', 'bar', 'baz']
my_func(*my_args)

The asterisk tells Python "take this list and treat it as the
positional arguments". Often when you don't know in advance what the
arguments are giong to be, this is a lot easier. The same is true of
keyword arguments; instead of

my_func(foo=bar, baz=quux)

you can build a dictionary and pass it to the function:

my_kwargs = {'foo': 'bar', 'baz': 'quux'}
my_func(**my_kwargs)

The double-asterisk tells Python "take this dictionary and treat it as
the keyword arguments".

That's why there are lots of places in Django where you'll see things like

some_func(*args, **kwargs)

What's happened is that the positional arguments have been put into a
list called 'args' as they were figured out, and the keyword arguments
into a dictionary called 'kwargs' -- the names serve as a reminder of
what they're for -- and then the list and the dictionary are handed
off to the function.

--
"May the forces of evil become confused on the way to your house."
-- George Carlin

David Reynolds

unread,
Jun 5, 2006, 8:38:43 AM6/5/06
to django...@googlegroups.com

Thanks for clearing that up, I'd often wondered what they were ;)

Cheers,

Dave
--
David Reynolds
da...@reynoldsfamily.org.uk

Reply all
Reply to author
Forward
0 new messages