Created
August 26, 2014 14:24
-
-
Save tomleo/5ba37353acb467311a69 to your computer and use it in GitHub Desktop.
Examples showing the flexibility of passing args and kwargs to python functions.
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
import sys | |
num = 0 | |
def printNum(func): | |
def pprint(*args, **kwargs): | |
global num | |
num += 1 | |
sys.stdout.write(u'%s: ' % num) | |
sys.stdout.write(func(*args, **kwargs)) | |
sys.stdout.write(u'\n') | |
return pprint | |
@printNum | |
def func1(a, b, c, d): | |
return "%s, %s, %s, %s" % (a, b, c, d) | |
@printNum | |
def func2(a, b, c, d=4): | |
return "%s, %s, %s, %s" % (a, b, c, d) | |
# 1. Pass in as positional arguments | |
func1(1, 2, 3, 4) | |
# 2. Pass in as named kw arguments | |
func1(d=4, c=3, b=2, a=1) | |
# 3. This is the same as passing in named kw arguments | |
func1(**dict(a=1, b=2, c=3, d=4)) | |
# 4. This is the same as passing in named kw arguments | |
func1(**{ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }) | |
# 5. You can mix positional and kwargs | |
func1(1, 2, d=4, c=3) | |
# 6. This isthe same as the signature above | |
func1(1,2,**{ 'c': 3, 'd': 4 }) | |
# 7. You cannot pass the value for a formal parameter as both a positional argument and a kwargument | |
try: | |
func1(4,3,**{ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }) | |
except TypeError: | |
print "TypeError: func1() got multiple values for keyword argument 'a'" | |
# 7. Functions with default values can be passed values as a positional argument | |
func2(1, 2, 3, 4) | |
# 8. Functions with default values can be passed values as kwargs | |
func2(d=4, c=3, b=2, a=1) | |
# 9. Functions with default values can be left off completly | |
func2(1, 2, 3) | |
func2(c=3, b=2, a=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment