Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.26 KB | None | 0 0
  1. >>> def print_keyword_args(**kwargs):
  2. ... # kwargs is a dict of the keyword args passed to the function
  3. ... for key, value in kwargs.iteritems():
  4. ... print "%s = %s" % (key, value)
  5. ...
  6. >>> print_keyword_args(first_name="John", last_name="Doe")
  7. first_name = John
  8. last_name = Doe
  9.  
  10. >>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
  11. >>> print_keyword_args(**kwargs)
  12. first_name = Bobby
  13. last_name = Smith
  14.  
  15. func(a=1, b=2, c=3)
  16.  
  17. args = {'a': 1, 'b': 2, 'c':3}
  18. func(**args)
  19.  
  20. args = {'name': person.name}
  21. if hasattr(person, "address"):
  22. args["address"] = person.address
  23. func(**args) # either expanded to func(name=person.name) or
  24. # func(name=person.name, address=person.address)
  25.  
  26. def setstyle(**styles):
  27. for key, value in styles.iteritems(): # styles is a regular dictionary
  28. setattr(someobject, key, value)
  29.  
  30. setstyle(color="red", bold=False)
  31.  
  32. def myDo(what, where, why):
  33. if what == 'swim':
  34. doSwim(where, why)
  35. elif what == 'walk':
  36. doWalk(where, why)
  37. ...
  38.  
  39. elif what == 'drive':
  40. doDrive(where, why, vehicle)
  41.  
  42. def myDo(what, where, why, **kwargs):
  43. if what == 'drive':
  44. doDrive(where, why, **kwargs)
  45. elif what == 'swim':
  46. doSwim(where, why, **kwargs)
  47.  
  48. def f(a = 0, *args, **kwargs):
  49. print("Received by f(a, *args, **kwargs)")
  50. print("=> f(a=%s, args=%s, kwargs=%s" % (a, args, kwargs))
  51. print("Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)")
  52. g(10, 11, 12, *args, d = 13, e = 14, **kwargs)
  53.  
  54. def g(f, g = 0, *args, **kwargs):
  55. print("Received by g(f, g = 0, *args, **kwargs)")
  56. print("=> g(f=%s, g=%s, args=%s, kwargs=%s)" % (f, g, args, kwargs))
  57.  
  58. print("Calling f(1, 2, 3, 4, b = 5, c = 6)")
  59. f(1, 2, 3, 4, b = 5, c = 6)
  60.  
  61. Calling f(1, 2, 3, 4, b = 5, c = 6)
  62. Received by f(a, *args, **kwargs)
  63. => f(a=1, args=(2, 3, 4), kwargs={'c': 6, 'b': 5}
  64. Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)
  65. Received by g(f, g = 0, *args, **kwargs)
  66. => g(f=10, g=11, args=(12, 2, 3, 4), kwargs={'c': 6, 'b': 5, 'e': 14, 'd': 13})
  67.  
  68. def args_kwargs_test(arg1, arg2, arg3):
  69. print "arg1:", arg1
  70. print "arg2:", arg2
  71. print "arg3:", arg3
  72.  
  73. #args can either be a "list" or "tuple"
  74. >>> args = ("two", 3, 5)
  75. >>> args_kwargs_test(*args)
  76.  
  77. #keyword argument "kwargs" has to be a dictionary
  78. >>> kwargs = {"arg3":3, "arg2":'two', "arg1":5}
  79. >>> args_kwargs_test(**kwargs)
  80.  
  81. def test(**kwargs):
  82. print kwargs['a']
  83. print kwargs['b']
  84. print kwargs['c']
  85.  
  86.  
  87. args = { 'b': 2, 'c': 3}
  88.  
  89. test( a=1, **args )
  90.  
  91. 1
  92. 2
  93. 3
  94.  
  95. def function1(param1,param2="arg2",param3="arg3"):
  96. print("n"+str(param1)+" "+str(param2)+" "+str(param3)+"n")
  97.  
  98. function1(1) #1 arg2 arg3 #1 positional arg
  99. function1(param1=1) #1 arg2 arg3 #1 named arg
  100. function1(1,param2=2) #1 2 arg3 #1 positional arg, 1 named arg
  101. function1(param1=1,param2=2) #1 2 arg3 #2 named args
  102. function1(param2=2, param1=1) #1 2 arg3 #2 named args out of order
  103. function1(1, param3=3, param2=2) #1 2 3 #
  104.  
  105. #function1() #invalid: required argument missing
  106. #function1(param2=2,1) #invalid: SyntaxError: non-keyword arg after keyword arg
  107. #function1(1,param1=11) #invalid: TypeError: function1() got multiple values for argument 'param1'
  108. #function1(param4=4) #invalid: TypeError: function1() got an unexpected keyword argument 'param4'
  109.  
  110. def function2(param1, *tupleParams, param2, param3, **dictionaryParams):
  111. print("param1: "+ param1)
  112. print("param2: "+ param2)
  113. print("param3: "+ param3)
  114. print("custom tuple params","-"*10)
  115. for p in tupleParams:
  116. print(str(p) + ",")
  117. print("custom named params","-"*10)
  118. for k,v in dictionaryParams.items():
  119. print(str(k)+":"+str(v))
  120.  
  121. function2("arg1",
  122. "custom param1",
  123. "custom param2",
  124. "custom param3",
  125. param3="arg3",
  126. param2="arg2",
  127. customNamedParam1 = "val1",
  128. customNamedParam2 = "val2"
  129. )
  130.  
  131. # Output
  132. #
  133. #param1: arg1
  134. #param2: arg2
  135. #param3: arg3
  136. #custom tuple params ----------
  137. #custom param1,
  138. #custom param2,
  139. #custom param3,
  140. #custom named params ----------
  141. #customNamedParam2:val2
  142. #customNamedParam1:val1
  143.  
  144. tupleCustomArgs = ("custom param1", "custom param2", "custom param3")
  145. dictCustomNamedArgs = {"customNamedParam1":"val1", "customNamedParam2":"val2"}
  146.  
  147. function2("arg1",
  148. *tupleCustomArgs, #note *
  149. param3="arg3",
  150. param2="arg2",
  151. **dictCustomNamedArgs #note **
  152. )
  153.  
  154. function2("arg1",
  155. tupleCustomArgs, #omitting *
  156. param3="arg3",
  157. param2="arg2",
  158. **dictCustomNamedArgs
  159. )
  160.  
  161. param1: arg1
  162. param2: arg2
  163. param3: arg3
  164. custom tuple params ----------
  165. ('custom param1', 'custom param2', 'custom param3'),
  166. custom named params ----------
  167. customNamedParam2:val2
  168. customNamedParam1:val1
  169.  
  170. function2("arg1",
  171. *tupleCustomArgs,
  172. param3="arg3",
  173. param2="arg2",
  174. dictCustomNamedArgs #omitting **
  175. )
  176.  
  177. dictCustomNamedArgs
  178. ^
  179. SyntaxError: non-keyword arg after keyword arg
  180.  
  181. def print_wrap(arg1, *args, **kwargs):
  182. print(arg1)
  183. print(args)
  184. print(kwargs)
  185. print(arg1, *args, **kwargs)
  186.  
  187. >>> print_wrap('one', 'two', 'three', end='blah', sep='--')
  188. one
  189. ('two', 'three')
  190. {'end': 'blah', 'sep': '--'}
  191. one--two--threeblah
  192.  
  193. >>> print_wrap('blah', dead_arg='anything')
  194. TypeError: 'dead_arg' is an invalid keyword argument for this function
  195.  
  196. #! /usr/bin/env python
  197. #
  198. def g( **kwargs) :
  199. print ( "In g ready to print kwargs" )
  200. print kwargs
  201. print ( "in g, calling f")
  202. f ( **kwargs )
  203. print ( "In g, after returning from f")
  204.  
  205. def f( **kwargs ) :
  206. print ( "in f, printing kwargs")
  207. print ( kwargs )
  208. print ( "In f, after printing kwargs")
  209.  
  210.  
  211. g( a="red", b=5, c="Nassau")
  212.  
  213. g( q="purple", w="W", c="Charlie", d=[4, 3, 6] )
  214.  
  215. $ python kwargs_demo.py
  216. In g ready to print kwargs
  217. {'a': 'red', 'c': 'Nassau', 'b': 5}
  218. in g, calling f
  219. in f, printing kwargs
  220. {'a': 'red', 'c': 'Nassau', 'b': 5}
  221. In f, after printing kwargs
  222. In g, after returning from f
  223. In g ready to print kwargs
  224. {'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
  225. in g, calling f
  226. in f, printing kwargs
  227. {'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
  228. In f, after printing kwargs
  229. In g, after returning from f
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement