Guest User

Untitled

a guest
May 27th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.04 KB | None | 0 0
  1. def foo(param1, *param2):
  2. def bar(param1, **param2):
  3.  
  4. In [1]: def foo(*args):
  5. ...: for a in args:
  6. ...: print a
  7. ...:
  8. ...:
  9.  
  10. In [2]: foo(1)
  11. 1
  12.  
  13.  
  14. In [4]: foo(1,2,3)
  15. 1
  16. 2
  17. 3
  18.  
  19. In [5]: def bar(**kwargs):
  20. ...: for a in kwargs:
  21. ...: print a, kwargs[a]
  22. ...:
  23. ...:
  24.  
  25. In [6]: bar(name='one', age=27)
  26. age 27
  27. name one
  28.  
  29. def foo(kind, *args, **kwargs):
  30. pass
  31.  
  32. In [9]: def foo(bar, lee):
  33. ...: print bar, lee
  34. ...:
  35. ...:
  36.  
  37. In [10]: l = [1,2]
  38.  
  39. In [11]: foo(*l)
  40. 1 2
  41.  
  42. first, *rest = [1,2,3,4]
  43. first, *l, last = [1,2,3,4]
  44.  
  45. def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
  46. pass
  47.  
  48. def foo(x,y,z):
  49. print("x=" + str(x))
  50. print("y=" + str(y))
  51. print("z=" + str(z))
  52.  
  53. >>> mylist = [1,2,3]
  54. >>> foo(*mylist)
  55. x=1
  56. y=2
  57. z=3
  58.  
  59. >>> mydict = {'x':1,'y':2,'z':3}
  60. >>> foo(**mydict)
  61. x=1
  62. y=2
  63. z=3
  64.  
  65. >>> mytuple = (1, 2, 3)
  66. >>> foo(*mytuple)
  67. x=1
  68. y=2
  69. z=3
  70.  
  71. >>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
  72. >>> foo(**mydict)
  73. Traceback (most recent call last):
  74. File "<stdin>", line 1, in <module>
  75. TypeError: foo() got an unexpected keyword argument 'badnews'
  76.  
  77. def foo(param1, *param2):
  78. print param1
  79. print param2
  80.  
  81. def bar(param1, **param2):
  82. print param1
  83. print param2
  84.  
  85. foo(1,2,3,4,5)
  86. bar(1,a=2,b=3)
  87.  
  88. 1
  89. (2, 3, 4, 5)
  90. 1
  91. {'a': 2, 'b': 3}
  92.  
  93. >>> x = xrange(3) # create our *args - an iterable of 3 integers
  94. >>> xrange(*x) # expand here
  95. xrange(0, 2, 2)
  96.  
  97. >>> foo = 'FOO'
  98. >>> bar = 'BAR'
  99. >>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
  100. 'this is foo, FOO and bar, BAR'
  101.  
  102. def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
  103. return arg, kwarg, args, kwarg2, kwargs
  104.  
  105. >>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
  106. (1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
  107.  
  108. def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
  109. return arg, kwarg, kwarg2, kwargs
  110.  
  111. >>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
  112. (1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
  113.  
  114. >>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
  115. Traceback (most recent call last):
  116. File "<stdin>", line 1, in <module>
  117. TypeError: foo() takes from 1 to 2 positional arguments
  118. but 5 positional arguments (and 1 keyword-only argument) were given
  119.  
  120. def bar(*, kwarg=None):
  121. return kwarg
  122.  
  123. >>> bar('kwarg')
  124. Traceback (most recent call last):
  125. File "<stdin>", line 1, in <module>
  126. TypeError: bar() takes 0 positional arguments but 1 was given
  127.  
  128. >>> bar(kwarg='kwarg')
  129. 'kwarg'
  130.  
  131. def foo(a, b=10, *args, **kwargs):
  132. '''
  133. this function takes required argument a, not required keyword argument b
  134. and any number of unknown positional arguments and keyword arguments after
  135. '''
  136. print('a is a required argument, and its value is {0}'.format(a))
  137. print('b not required, its default value is 10, actual value: {0}'.format(b))
  138. # we can inspect the unknown arguments we were passed:
  139. # - args:
  140. print('args is of type {0} and length {1}'.format(type(args), len(args)))
  141. for arg in args:
  142. print('unknown arg: {0}'.format(arg))
  143. # - kwargs:
  144. print('kwargs is of type {0} and length {1}'.format(type(kwargs),
  145. len(kwargs)))
  146. for kw, arg in kwargs.items():
  147. print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
  148. # But we don't have to know anything about them
  149. # to pass them to other functions.
  150. print('Args or kwargs can be passed without knowing what they are.')
  151. # max can take two or more positional args: max(a, b, c...)
  152. print('e.g. max(a, b, *args) n{0}'.format(
  153. max(a, b, *args)))
  154. kweg = 'dict({0})'.format( # named args same as unknown kwargs
  155. ', '.join('{k}={v}'.format(k=k, v=v)
  156. for k, v in sorted(kwargs.items())))
  157. print('e.g. dict(**kwargs) (same as {kweg}) returns: n{0}'.format(
  158. dict(**kwargs), kweg=kweg))
  159.  
  160. foo(a, b=10, *args, **kwargs)
  161.  
  162. a is a required argument, and its value is 1
  163. b not required, its default value is 10, actual value: 2
  164. args is of type <type 'tuple'> and length 2
  165. unknown arg: 3
  166. unknown arg: 4
  167. kwargs is of type <type 'dict'> and length 3
  168. unknown kwarg - kw: e, arg: 5
  169. unknown kwarg - kw: g, arg: 7
  170. unknown kwarg - kw: f, arg: 6
  171. Args or kwargs can be passed without knowing what they are.
  172. e.g. max(a, b, *args)
  173. 4
  174. e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
  175. {'e': 5, 'g': 7, 'f': 6}
  176.  
  177. def bar(a):
  178. b, c, d, e, f = 2, 3, 4, 5, 6
  179. # dumping every local variable into foo as a keyword argument
  180. # by expanding the locals dict:
  181. foo(**locals())
  182.  
  183. a is a required argument, and its value is 100
  184. b not required, its default value is 10, actual value: 2
  185. args is of type <type 'tuple'> and length 0
  186. kwargs is of type <type 'dict'> and length 4
  187. unknown kwarg - kw: c, arg: 3
  188. unknown kwarg - kw: e, arg: 5
  189. unknown kwarg - kw: d, arg: 4
  190. unknown kwarg - kw: f, arg: 6
  191. Args or kwargs can be passed without knowing what they are.
  192. e.g. max(a, b, *args)
  193. 100
  194. e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
  195. {'c': 3, 'e': 5, 'd': 4, 'f': 6}
  196.  
  197. def foo(a, b, c, d=0, e=100):
  198. # imagine this is much more code than a simple function call
  199. preprocess()
  200. differentiating_process_foo(a,b,c,d,e)
  201. # imagine this is much more code than a simple function call
  202. postprocess()
  203.  
  204. def bar(a, b, c=None, d=0, e=100, f=None):
  205. preprocess()
  206. differentiating_process_bar(a,b,c,d,e,f)
  207. postprocess()
  208.  
  209. def baz(a, b, c, d, e, f):
  210. ... and so on
  211.  
  212. def decorator(function):
  213. '''function to wrap other functions with a pre- and postprocess'''
  214. @functools.wraps(function) # applies module, name, and docstring to wrapper
  215. def wrapper(*args, **kwargs):
  216. # again, imagine this is complicated, but we only write it once!
  217. preprocess()
  218. function(*args, **kwargs)
  219. postprocess()
  220. return wrapper
  221.  
  222. @decorator
  223. def foo(a, b, c, d=0, e=100):
  224. differentiating_process_foo(a,b,c,d,e)
  225.  
  226. @decorator
  227. def bar(a, b, c=None, d=0, e=100, f=None):
  228. differentiating_process_bar(a,b,c,d,e,f)
  229.  
  230. @decorator
  231. def baz(a, b, c=None, d=0, e=100, f=None, g=None):
  232. differentiating_process_baz(a,b,c,d,e,f, g)
  233.  
  234. @decorator
  235. def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
  236. differentiating_process_quux(a,b,c,d,e,f,g,h)
  237.  
  238. def test(a,b,c):
  239. print(a)
  240. print(b)
  241. print(c)
  242.  
  243. test(1,2,3)
  244. #output:
  245. 1
  246. 2
  247. 3
  248.  
  249. def test(a,b,c):
  250. print(a)
  251. print(b)
  252. print(c)
  253.  
  254. test(a=1,b=2,c=3)
  255. #output:
  256. 1
  257. 2
  258. 3
  259.  
  260. def test(a=0,b=0,c=0):
  261. print(a)
  262. print(b)
  263. print(c)
  264. print('-------------------------')
  265.  
  266. test(a=1,b=2,c=3)
  267. #output :
  268. 1
  269. 2
  270. 3
  271. -------------------------
  272.  
  273. def test(a=0,b=0,c=0):
  274. print(a)
  275. print(b)
  276. print(c)
  277. print('-------------------------')
  278.  
  279. test(1,2,3)
  280. # output :
  281. 1
  282. 2
  283. 3
  284. ---------------------------------
  285.  
  286. def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
  287. print(a+b)
  288.  
  289. my_tuple = (1,2)
  290. my_list = [1,2]
  291. my_dict = {'a':1,'b':2}
  292.  
  293. # Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
  294. sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
  295. sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
  296. sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
  297.  
  298. # output is 3 in all three calls to sum function.
  299.  
  300. def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
  301. sum = 0
  302. for a in args:
  303. sum+=a
  304. print(sum)
  305.  
  306. sum(1,2,3,4) #positional args sent to function sum
  307. #output:
  308. 10
  309.  
  310. def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
  311. sum=0
  312. for k,v in args.items():
  313. sum+=v
  314. print(sum)
  315.  
  316. sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
  317.  
  318. x = [1, 2, 3]
  319. y = [4, 5, 6]
  320.  
  321. unzip_x, unzip_y = zip(*zip(x, y))
  322.  
  323. zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
  324.  
  325. In function *construction* In function *call*
  326. =======================================================================
  327. | def f(*args): | def f(a, b):
  328. *args | for arg in args: | return a + b
  329. | print(arg) | args = (1, 2)
  330. | f(1, 2) | f(*args)
  331. ----------|--------------------------------|---------------------------
  332. | def f(a, b): | def f(a, b):
  333. **kwargs | return a + b | return a + b
  334. | def g(**kwargs): | kwargs = dict(a=1, b=2)
  335. | return f(**kwargs) | f(**kwargs)
  336. | g(a=1, b=2) |
  337. -----------------------------------------------------------------------
  338.  
  339. >>> (0, *range(1, 4), 5, *range(6, 8))
  340. (0, 1, 2, 3, 5, 6, 7)
  341. >>> [0, *range(1, 4), 5, *range(6, 8)]
  342. [0, 1, 2, 3, 5, 6, 7]
  343. >>> {0, *range(1, 4), 5, *range(6, 8)}
  344. {0, 1, 2, 3, 5, 6, 7}
  345. >>> d = {'one': 1, 'two': 2, 'three': 3}
  346. >>> e = {'six': 6, 'seven': 7}
  347. >>> {'zero': 0, **d, 'five': 5, **e}
  348. {'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
  349.  
  350. >>> range(*[1, 10], *[2])
  351. range(1, 10, 2)
  352.  
  353. def __init__(self, *args, **kwargs):
  354. for attribute_name, value in zip(self._expected_attributes, args):
  355. setattr(self, attribute_name, value)
  356. if kwargs.has_key(attribute_name):
  357. kwargs.pop(attribute_name)
  358.  
  359. for attribute_name in kwargs.viewkeys():
  360. setattr(self, attribute_name, kwargs[attribute_name])
  361.  
  362. class RetailItem(Item):
  363. _expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
  364.  
  365. class FoodItem(RetailItem):
  366. _expected_attributes = RetailItem._expected_attributes + ['expiry_date']
  367.  
  368. food_item = FoodItem(name = 'Jam',
  369. price = 12.0,
  370. category = 'Foods',
  371. country_of_origin = 'US',
  372. expiry_date = datetime.datetime.now())
  373.  
  374. class ElectronicAccessories(RetailItem):
  375. _expected_attributes = RetailItem._expected_attributes + ['specifications']
  376. # Depend on args and kwargs to populate the data as needed.
  377. def __init__(self, specifications = None, *args, **kwargs):
  378. self.specifications = specifications # Rest of attributes will make sense to parent class.
  379. super(ElectronicAccessories, self).__init__(*args, **kwargs)
  380.  
  381. usb_key = ElectronicAccessories(name = 'Sandisk',
  382. price = '$6.00',
  383. category = 'Electronics',
  384. country_of_origin = 'CN',
  385. specifications = '4GB USB 2.0/USB 3.0')
  386.  
  387. >>> def foo(*arg,**kwargs):
  388. ... print arg
  389. ... print kwargs
  390. >>>
  391. >>> a = (1, 2, 3)
  392. >>> b = {'aa': 11, 'bb': 22}
  393. >>>
  394. >>>
  395. >>> foo(*a,**b)
  396. (1, 2, 3)
  397. {'aa': 11, 'bb': 22}
  398. >>>
  399. >>>
  400. >>> foo(a,**b)
  401. ((1, 2, 3),)
  402. {'aa': 11, 'bb': 22}
  403. >>>
  404. >>>
  405. >>> foo(a,b)
  406. ((1, 2, 3), {'aa': 11, 'bb': 22})
  407. {}
  408. >>>
  409. >>>
  410. >>> foo(a,*b)
  411. ((1, 2, 3), 'aa', 'bb')
  412. {}
  413.  
  414. class base(object):
  415. def __init__(self, base_param):
  416. self.base_param = base_param
  417.  
  418.  
  419. class child1(base): # inherited from base class
  420. def __init__(self, child_param, *args) # *args for non-keyword args
  421. self.child_param = child_param
  422. super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
  423.  
  424. class child2(base):
  425. def __init__(self, child_param, **kwargs):
  426. self.child_param = child_param
  427. super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
  428.  
  429. c1 = child1(1,0)
  430. c2 = child2(1,base_param=0)
  431. print c1.base_param # 0
  432. print c1.child_param # 1
  433. print c2.base_param # 0
  434. print c2.child_param # 1
  435.  
  436. def args(normal_arg, *argv):
  437. print ("normal argument:",normal_arg)
  438.  
  439. for arg in argv:
  440. print("Argument in list of arguments from *argv:", arg)
  441.  
  442. args('animals','fish','duck','bird')
  443.  
  444. normal argument: animals
  445. Argument in list of arguments from *argv: fish
  446. Argument in list of arguments from *argv: duck
  447. Argument in list of arguments from *argv: bird
  448.  
  449. def who(**kwargs):
  450. if kwargs is not None:
  451. for key, value in kwargs.items():
  452. print ("Your %s is %s." %(key,value))
  453.  
  454. who (name="Nikola", last_name="Tesla", birthday = "7.10.1856", birthplace = "Croatia")
  455.  
  456. Your name is Nikola.
  457. Your last_name is Tesla.
  458. Your birthday is 7.10.1856.
  459. Your birthplace is Croatia.
  460.  
  461. def f(normal_input, *args, **kw):
  462. # Print the length of args and kw in a friendly format
  463. print("len(args) = {} and len(kw) = {}".format(len(args), len(kw)))
  464.  
  465. l = list(range(5))
  466. d = {"k0":"v0", "k1":"v1"}
  467.  
  468. f(42, 0, 1, 2, 3, 4, 5) # len(args) = 6 and len(kw) = 0
  469.  
  470. f(42, l) # len(args) = 1 and len(kw) = 0
  471. f(42, d) # len(args) = 1 and len(kw) = 0
  472.  
  473. f(42, *l) # len(args) = 5 and len(kw) = 0
  474. f(42, *d) # len(args) = 2 and len(kw) = 0
  475.  
  476. try:
  477. f(42, **l) # Gives an error
  478. except TypeError:
  479. print("l in f(**l) is not a dictionary!")
  480.  
  481. f(42, **d) # len(args) = 0 and len(kw) = 2
  482.  
  483. # Without explicitly feeding normal_input
  484. # l[0] becomes normal_input
  485. f(*l) # len(args) = 4 and len(kw) = 0
  486.  
  487. # Let's try everything now
  488. f(42, 420, 4200, *l, **d) # len(args) = 7 and len(kw) = 2
Add Comment
Please, Sign In to add comment