Skip to content

Instantly share code, notes, and snippets.

@gregorykremler
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregorykremler/6aa60613027508bc202e to your computer and use it in GitHub Desktop.
Save gregorykremler/6aa60613027508bc202e to your computer and use it in GitHub Desktop.
Examples of pythons *args + **kwargs magic variables.
# in a function definition
# *args and **kwargs allow you to pass a variable number of args to a function
# *args is for a non-keyworded variable length argument list
def test_var_args(f_arg, *argv):
print "first normal arg:", f_arg
for arg in argv:
print "another arg through *argv:", arg
# test_var_args('Matt', 1, 2, 3, {}, 'bologna')
# **kwargs is for keyworded varaible length arguments (ie, named arguments)
def greet_me(**kwargs):
if kwargs is not None:
for key, value in kwargs.iteritems():
print '%s == %s' % (key, value)
# greet_me(name='Greg', height="5'7\"", gender='male')
# in a function call
# *args and **kwargs "unpack" arguments provided with this special syntax
def test_args_kwargs(arg1, arg2, arg3):
print 'arg1:', arg1
print 'arg2:', arg2
print 'arg3:', arg3
# args = ('banana', 3, [])
# test_args_kwargs(*args)
# kwargs = {'arg1': 'a', 'arg2': 15, 'arg3': None}
# test_args_kwargs(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment