Last active
November 6, 2020 22:04
-
-
Save c0ldlimit/4091273 to your computer and use it in GitHub Desktop.
Python: How to use *args and **kwargs #python #args #kwargs #c0ldlimit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This example passes one formal (positional) argument, and two more variable length arguments. | |
def test_var_args(farg, *args): | |
print "formal arg:", farg | |
for arg in args: | |
print "another arg:", arg | |
test_var_args(1, "two", 3) | |
# Here is an example of how to use the keyworded form. Again, one formal argument and two keyworded variable arguments are passed. | |
def test_var_kwargs(farg, **kwargs): | |
print "formal arg:", farg | |
for key in kwargs: | |
print "another keyword arg: %s: %s" % (key, kwargs[key]) | |
test_var_kwargs(farg=1, myarg2="two", myarg3=3) | |
# This special syntax can be used, not only in function definitions, but also when calling a function. | |
def test_var_args_call(arg1, arg2, arg3): | |
print "arg1:", arg1 | |
print "arg2:", arg2 | |
print "arg3:", arg3 | |
args = ("two", 3) | |
test_var_args_call(1, *args) | |
# Here is an example using the keyworded form when calling a function: | |
def test_var_args_call(arg1, arg2, arg3): | |
print "arg1:", arg1 | |
print "arg2:", arg2 | |
print "arg3:", arg3 | |
kwargs = {"arg3": 3, "arg2": "two"} | |
test_var_args_call(1, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added to it https://gist.github.com/anonymous/271d6160cdd90a482b40