-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.py
More file actions
940 lines (678 loc) · 24.7 KB
/
Functions.py
File metadata and controls
940 lines (678 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
########## FUNCTIONS ##########
## A function is able to:
# cause some effect
# evaluate a value
## Every function has two parts:
# 1. The function signature defines the name of the function and any inputs it expects.
# 2. The function body contains the code that runs every time the function is used.
def multiply(x, y): # Function signature
# Function body below
product = x * y
return product
## The function signature has four parts:
# 1. The def keyword
# 2. The function name, multiply
# 3. The parameter list, (x, y)
# 4. A colon (:) at the end of the line
## Function name STARTS by a letter and contains ONLY letters, numbers and _
# You MUST NOT have a function and a variable of the same name
# It's legal, and possible, to have a variable named the same as a function's parameter
# the meaning of the argument is dictated by its name, not by its position = keyword argument passing
## Functions come from at least three places:
# 1- from Python itself - numerous functions (like print()) are an integral part of Python,
# and are always available without any additional effort on behalf of the programmer;
# we call these functions built-in functions;
# 2- from Python's preinstalled modules - a lot of functions, very useful ones,
# but used significantly less often than built-in ones, are available in a number
# of modules installed together with Python; the use of these functions requires
# some additional steps from the programmer in order to make them fully accessible
# 3- directly from your code - you can write your own functions, place them inside
# your code, and use them freely
## The process for executing a function can be summarized in three steps:
# 1. The function is called, and any arguments are passed to the function as input.
# 2. The function executes, and some action is performed with the arguments.
# 3. The function returns, and the original function call is replaced with the return value.
### RETURN
# 1- you are always allowed to ignore the function's result, and be satisfied with
# the function's effect (if the function has any)
# 2- if a function is intented to return a useful result, it must contain the second
# variant of the return instruction.
# 3- all part AFTER return is IGNORED
## a return closes the function (somehow like a break in loops)
def hi():
return
print("Hi!") # ignored
# (None)
## return without an expression
def happyNewYear(wishes = True):
print("Three...")
print("Two...")
print("One...")
if not wishes: # if wishes = False
return # return None
print("Happy New Year!")
happyNewYear ()
# Three...
# Two...
# One...
# Happy New Year!
## return with an expression
def boringFunction():
return 123
x = boringFunction()
print("The boringFunction has returned its result. It's:", x)
# The boringFunction has returned its result. It's: 123
## ignore the return value
def boringFunction():
print("'Boredom Mode' ON.")
return 123
print("This lesson is interesting!")
boringFunction()
print("This lesson is boring...")
# This lesson is interesting!
# 'Boredom Mode' ON.
# This lesson is boring... # return value 123 is not used and it is fine
## return / none default if no result from the function
def strangeFunction(n):
if(n % 2 == 0):
return True
print(strangeFunction(2))
print(strangeFunction(1))
True
# (None) # 1%2 = 1 ==> return = None because nothing configured in the function for this case
## collect a function return
def my_fonction():
return 42
my_variable = my_fonction()
print(my_variable)
# 42
### SCOPE
# The function func() has a different scope than the code that exists outside of the function
# We can name an object inside func() the same name as something outside func() and Python keep the two separated.
# 1- a var defined out of the function is usable into a function
# 2- a var defined in a function is not recognised out of it
# 3- if a var has the same name into a function and out of it, the function uses the var as defined into it
# 4- with lists, if a list is processed by a function, it will reflect the changes outside the function
## Python resolves scope in the order in which each scope appears in the list LEGB
# 1- Local (L): The local, or current, scope. The scope that the Python interpreter is currently working in
# 2- Enclosing (E): The enclosing scope. This is the scope one level up from the local scope
# If the local scope is an inner function, the enclosing scope is the scope of the outer function
# If the scope is a top-level function, the enclosing scope is the same as the global scope
# 3- Global (G): The global scope, which is the top-most scope in the script and all of the names defined in the script that are not contained in a function body
# 4- Built-in (B): The built-in scope contains all of the names, such as keywords, that are built-in to Python
def func(data):
data = [7, 23, 42]
print('Function scope: ', data)
data = ['Peter', 'Paul', 'Mary']
func(data) # prefer its own "data" variable
print('Outer scope: ', data) # as "data" from func(data) is not global, data = ['Peter', 'Paul', 'Mary'] is used
# Function scope: [7, 23, 42]
# Outer scope: ['Peter', 'Paul', 'Mary']
## variable scope LOCAL vs GLOBAL
total = 0
def add_to_total(n):
total = total + n
add_to_total(5)
print(total)
# Traceback (most recent call last):
# File "C:\Users\bfrerot\OneDrive - ID Logistics\Documents\Python\IDLE.py", line 4, in <module>
# add_to_total(5)
# File "C:\Users\bfrerot\OneDrive - ID Logistics\Documents\Python\IDLE.py", line 3, in add_to_total
# total = total + n
# UnboundLocalError: local variable 'total' referenced before assignment
# The problem here is that the script attempts to make an assignment to
# the variable total, which creates a new name in the local scope. Then,when Python executes
# the right-hand side of the assignment it finds the name total in the local scope with
# nothing assigned to it yet.
# We need to use the GLOBAL keyword to fix it:
total = 0
def add_to_total(n):
global total
total = total + n
add_to_total(5)
print(total)
# 5
## interaction with variables
x = 1
def a(x):
return 2 * x
print(x)
# 1
x = 2 + a(x)
print(x)
# 4 # x value changed
print(a(x))
# 8
print(x)
# 4 # x value did not changed thru the a() function
num = 1
def func(x):
x = x + 3
print(x)
func(num)
# 4
print(num)
# 1 num value did not changed thru the a() function
num = 1
def func(y):
global num # num becomes global, the function can change its global value
num = y + 3
print(num)
func(num)
# 4
print(num)
# 4 # num value modified
def increment(c, num):
c.count += 1 # increments .count de l'objet counter
num += 1 # num += 1 : incrémente la variable LOCALE num
# Modifier num dans la fonction ne modifie pas la variable number en dehors de la fonction
class Counter:
def __init__(self):
self.count = 0
counter = Counter() # counter.count = 0
number = 0
for i in range(0, 100):
increment(counter, number)
print(
"counter is "
+ str(counter.count)
+ ", number of times is "
+ str(number)
)
# counter is 100, number of times is 0
## interaction with list
def myFunction(myList1):
print(myList1)
del myList1[0]
myList2 = [2, 3]
myFunction(myList2)
print(myList2)
# [3]
def test(lst):
del lst[3]
lst[3] = 'ram'
return lst
testlist=[0,1,2,3,4]
print (test(testlist))
# [0, 1, 2, 'ram']
### Function VS Methods
# A method is a specific kind of function
# it behaves like a function and looks like a function but differs in the way in which it acts and invocation style
# result = data.method(arg)
# methods are used to play with lists
### ARGUMENTS, PARAMETERS
# Default arguments
# if not specified at the invokation, the default value is used
def introduction(first_name, last_name="Smith"):
print("Hello, my name is", first_name, last_name)
introduction("James", "Doe")
introduction("Henry")
# Hello, my name is James Doe
# Hello, my name is Henry Smith
class Class:
def __init__(self, val=0):
self.val = val
# valid invokations
object_1 = Class() # default is used
print(object_1.val)
# 0
object_2 = Class(1) # value is forced
print(object_2.val)
# 1
object_3 = Class(None) # None is a value
print(object_3.val)
# None
object_4 = Class(True) # True is a value
print(object_4.val)
# True
## *args ==> Many parameters FLEXIBLE
# to define functions that accept variable number of arguments
def add(*args):
return sum(args)
print(add(1, 1, 1))
# 3
print(add(1))
# 1
### POSITIONNAL VS KEYWORDS arguments
# MUST NOT follow keyword arguments
def subtra(a, b):
print(a - b)
subtra(5, b=2)
# 3
subtra(a=5, 2)
# Syntax Error
def add_numbers(a, b=2, c):
print(a + b + c)
add_numbers(a=1, c=3)
# Syntax Error
def add_numbers(a, c, b=2):
print(a + b + c)
add_numbers(a=1, c=3)
# 6
def test(x, y=23, z=10):
print('x is', x, 'and y is', y, 'and z is', z)
test(3, 7)
# x is 3 and y is 7 and z is 10
test(42, z=24)
# x is 42 and y is 23 and z is 24
test(z=60, x=100)
# x is 100 and y is 23 and z is 60
## parameters in order
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)
introduction("Luke", "Skywalker") # if parameter is not specified with an = + parameter value, default order is respected
# Hello, my name is Luke Skywalker
introduction("Jesse", "Quick")
# Hello, my name is Jesse Quick
introduction("Clark", "Kent")
# Hello, my name is Clark Kent
## parameters in disorder
def introduction(firstName, lastName):
print("Hello, my name is", firstName, lastName)
introduction(firstName = "James", lastName = "Bond")
introduction(lastName = "Skywalker", firstName = "Luke") # if parameters are set in a different order with an = + parameter, the function doesn't care and sort it in the right way
# Hello, my name is James Bond
# Hello, my name is Luke Skywalker
## default parameters
def introduction(firstName, lastName="Smith"):
print("Hello, my name is", firstName, lastName)
introduction("James")
# Hello, my name is James Smith # unique parameter = first (first name) + second with its default value
def fun(inp=2,out=3):
return inp * out
print (fun(out=2))
# 4
## multiple parameters (*par)
def fun(*val): # fun() accepts any multiple parameters
print(type(val))
lst=[1,2,3,4,5]
number = 400
fun(lst,number)
# <class 'tuple'> # ([1,2,3,4,5], 400) is tuple
## default parameter replaced
def introduction(firstName, lastName="Smith"):
print("Hello, my name is", firstName, lastName)
introduction("James","Doe")
# Hello, my name is James Doe # Smith (default parameter) is replaced by Doe (specified parameter)
## parameter usage
# a function may wait for x parameters but uses only a part of None of them, it's legal
def fun(x,y=6):
return x**3
print (fun(2))
# 8
def fun(data, *num ):
print(data)
fun("Earth", 2, True, "Jupiter")
# Earth
## list as a function parameter
def sumOfList(lst):
sum = 0
for elem in lst:
sum += elem
return sum
print(sumOfList([5, 4, 3]))
# 12
# IF we modify a list into a function, no global concept, it changes its value even outer of the function
# del, .append(), .pop(), .sort(), into a function will change its value outer as well
def my_function(my_list_1):
print("Print #1:", my_list_1)
print("Print #2:", my_list_2)
del my_list_1[0] # Pay attention to this line.
print("Print #3:", my_list_1)
print("Print #4:", my_list_2)
my_list_2 = [2, 3]
my_function(my_list_2)
print("Print #5:", my_list_2)
# #1: [2, 3]
# Print #2: [2, 3]
# Print #3: [3]
# Print #4: [3]
# Print #5: [3]
### OUTER/INNER Functions
# functions nesting
x = 5
def outer_func():
y = 3
def inner_func():
z = x + y
return z
return inner_func()
print (outer_func())
# 8
def quote(x):
def embed(y):
return x + y + x
return embed
dq = quote('"')
print(dq('Jane Doe'))
# "Jane Doe"
### DOCSTRING
# to create Documentation about a function
def multiply(x, y):
"""Return the product of two numbers x and y.""" # comment in function = docstring
product = x * y
return product
help(multiply)
# Help on function multiply in module __main__:
#
# multiply(x, y)
# Return the product of two numbers x and y. # comment returned when help function is used
### RETURN vs PRINT()
#invokink
def wishes():
print("My Wishes")
return "Happy Birthday"
wishes()
# My Wishes
#printing
def wishes():
print("My Wishes")
return "Happy Birthday"
print(wishes())
# My Wishes
# Happy Birthday
### INFINITE LOOP
# Example and correction with termination condition insertion
# whitout
def fun(a):
return a + fun(a + 3)
print(fun(25))
...
# [Previous line repeated 996 more times]
# RecursionError: maximum recursion depth exceeded
# with
def fun(a):
if a > 30:
return 3
else:
return a + fun(a + 3)
print(fun(25))
56 # 25 + 28 + fun(31)=3 --> 56
### RECURSIVITY
# Example
def fact(num):
if num == 1:
return 1
return fact(num - 1) * num
print(fact(4))
# 24
# Calcul of fact(4) :
# fact(4) = fact(3) * 4
# fact(3) = fact(2) * 3
# fact(2) = fact(1) * 2
# fact(1) = 1
# So :
# fact(2) = 1 * 2 = 2
# fact(3) = 2 * 3 = 6
# fact(4) = 6 * 4 = 24
# 24 (result)
### Exception handling
def spam(divideBy):
return 42 / divideBy
print(spam(2))
print(spam(12))
print(spam(0)) # Division by 0 error
print(spam(1))
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
return None # or any other default value
except Exception as e:
print(f'Unexpected error: {e}')
return None
print(spam(2))
# 21.0
print(spam(12))
# 3.5
print(spam(0))
# Error: Invalid argument.
# None
print(spam(1))
# 42.0
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')
# 21.0
# 3.5
# Error: Invalid argument. # jumps to except block
### CLOSURES
def outer(par):
loc = par
def inner():
return loc # = 1
return inner # = 1
var = 1
fun = outer(var)
print(fun())
# 1
def make_closure(par):
loc = par
def power(p):
return p ** loc
return power
fsqr = make_closure(2)
fcub = make_closure(3)
for i in range(5):
print(i, fsqr(i), fcub(i))
# 0 0 0
# 1 1 1
# 2 4 8
# 3 9 27
# 4 16 64
def func():
text = 'Paul'
names = lambda x: text + ' ' + x
return names
people = func()
print(people('Peter'))
# Paul Peter
def o(p):
def q():
return '*' * p
return q
r = o(1)
s = o(2)
print(r() + s())
# ***
### EXTENDED FUNCTION ARGUMENT SYNTAX
# ==> Reminder
# some functions can be invoked
# - without arguments
# - with a specific number of arguments with no exclusions
# - having default values for some parameters
# - arguments in any order if we are assigning keywords to all argument values, otherwise positional ones are the first ones on the arguments list
## *args and **kwargs
# *args and **kwargs should be put as the last two parameters in a function definition
# Their names could be changed because it is just a convention to name them "args" and "kwargs",
# but it’s more important to sustain the order of the parameters and leading asterisks
# Those two special parameters are responsible for handling any number of additional arguments (placed next after the expected arguments)
# passed to a called function:
# *args
# collects all unmatched positional arguments
# **kwargs
# collects all unmatched keyword arguments
def combiner(a, b, *args, **kwargs):
print(a, type(a))
print(b, type(b))
print(args, type(args))
print(kwargs, type(kwargs))
combiner(10, '20', 40, 60, 30, 10, 5, 8, argument1=50, argument2='66', )
# 10 <class 'int'>
# 20 <class 'str'>
# (40, 60, 30, 10, 5, 8) <class 'tuple'>
# {'argument1': 50, 'argument2': '66'} <class 'dict'>
def combiner(a, b, *args, **kwargs):
super_combiner(*args, **kwargs) # invokes super_combiner function below
def super_combiner(*my_args, **my_kwargs): # we use quite the same arguments names than above
print('my_args:', my_args)
print('my_kwargs', my_kwargs)
combiner(10, '20', 40, 60, 30, argument1=50, argument2='66')
# my_args: (40, 60, 30)
# my_kwargs {'argument1': 50, 'argument2': '66'}
## keywords arguments vs *args and **kwargs
def combiner(a, b, *args, c=20, **kwargs):
super_combiner(c, *args, **kwargs)
def super_combiner(my_c, *my_args, **my_kwargs):
print('my_args:', my_args)
print('my_c:', my_c)
print('my_kwargs', my_kwargs)
combiner(1, '1', 1, 1, c=2, argument1=1, argument2='1') # keyword argument between *args and **kwars ==> OK
# my_args: (1, 1)
# my_c: 2
# my_kwargs {'argument1': 1, 'argument2': '1'}
combiner(1, '1', 1, 1, argument1=1, argument2='1', c=2) # keyword argument after *args and **kwars ==> OK
# my_args: (1, 1)
# my_c: 2
# my_kwargs {'argument1': 1, 'argument2': '1'}
combiner(1, '1', c=2, 1, 1, argument1=1, argument2='1') # keyword argument before *args and **kwars ==> NOK
# SyntaxError: positional argument follows keyword argument
combiner(c=2, 1, '1', 1, 1, argument1=1, argument2='1') # keyword argument before positionnal arguments and *args and **kwars ==> NOK
# SyntaxError: positional argument follows keyword argument
### DECORATORS
# Decorators are used in:
# - validation of arguments
# - modification of arguments
# - modification of returned objects
# - measurement of execution time
# - message logging
# - thread synchronization
# - code refactorization
# - caching
## simple decorator – a function which accepts another function as its only argument, prints some details, and returns a function or other callable object
def simple_hello():
print("Hello from simple function!")
def simple_decorator(function):
print('We are about to call "{}"'.format(function.__name__))
return function
decorated = simple_decorator(simple_hello)
decorated()
# We are about to call "simple_hello"
# Hello from simple function!
## implementation of the decorator pattern introduces this syntax below:
def simple_decorator(function):
print('We are about to call "{}"'.format(function.__name__))
return function
@simple_decorator # must be followed by a def or a class, if we try to set a variable for instance ==> Syntax error
def simple_hello():
print("Hello from simple function!")
simple_hello()
# We are about to call "simple_hello"
# Hello from simple function!
## how the decorator can handle the arguments of the function being decorated
def simple_decorator(own_function): # decorator function is defined
def internal_wrapper(*args, **kwargs): # internal function which will "wrapp" things
print('"{}" was called with the following arguments'.format(own_function.__name__)) # 1
print('\t{}\n\t{}\n'.format(args, kwargs)) # 2
own_function(*args, **kwargs) # 3
print('Decorator is still operating') # 4
return internal_wrapper #==> applies 1,2,3 and 4
@simple_decorator # makes simple_decorator() a decorator
def combiner(*args, **kwargs): # linked to @simple_decorator
print("\tHello from the decorated function; received arguments:", args, kwargs) # 3
combiner('a', 'b', exec='yes')
# "combiner" was called with the following arguments # 1
# ('a', 'b') # 2
# {'exec': 'yes'} # 2
# # 2
# Hello from the decorated function; received arguments: ('a', 'b') {'exec': 'yes'} # 3
# Decorator is still operating # 4
## create a decorator with arguments and add a def layer
def warehouse_decorator(material): #3
def wrapper(our_function): #4
def internal_wrapper(*args): #5
print('<strong>*</strong> Wrapping items from {} with {}'.format(our_function.__name__, material)) #5.1
our_function(*args) #5.2
print() #5.3
return internal_wrapper #6
return wrapper #7
@warehouse_decorator('kraft') #2
def pack_books(*args):
print("We'll pack books:", args)
@warehouse_decorator('foil')
def pack_toys(*args):
print("We'll pack toys:", args)
@warehouse_decorator('cardboard')
def pack_fruits(*args):
print("We'll pack fruits:", args)
pack_books('Alice in Wonderland', 'Winnie the Pooh') #1
# <strong>*</strong> Wrapping items from pack_books with kraft #5.1
# We'll pack books: ('Alice in Wonderland', 'Winnie the Pooh') #5.2
# #5.3
pack_toys('doll', 'car')
# <strong>*</strong> Wrapping items from pack_toys with foil
# We'll pack toys: ('doll', 'car')
pack_fruits('plum', 'pear')
# <strong>*</strong> Wrapping items from pack_fruits with cardboard
# We'll pack fruits: ('plum', 'pear')
## Decorator stacking
def big_container(collective_material): #3
def wrapper(our_function): #3.1
def internal_wrapper(*args): #3.2
our_function(*args) # ignored as already invoked by 1st decorator
print('<strong>*</strong> The whole order would be packed with', collective_material) #3.3
print() #3.4
return internal_wrapper #3.5
return wrapper #3.6
def warehouse_decorator(material): #2
def wrapper(our_function): #2.1
def internal_wrapper(*args): #2.2
our_function(*args) #2.3
print('<strong>*</strong> Wrapping items from {} with {}'.format(our_function.__name__, material)) #2.4
return internal_wrapper #2.5
return wrapper #2.6
@big_container('plain cardboard') #3 ==> executed 2nd
@warehouse_decorator('bubble foil') #2 ==> executed 1st
def pack_books(*args):
print("We'll pack books:", args)
pack_books('Alice in Wonderland', 'Winnie the Pooh') # 1
# We'll pack books: ('Alice in Wonderland', 'Winnie the Pooh') #2.3 2.6
# <strong>*</strong> Wrapping items from pack_books with bubble foil #2.4 2.6
# <strong>*</strong> The whole order would be packed with plain cardboard #3.3 3.6
## Decorating functions with classes
class SimpleDecorator: #2
def __init__(self, own_function): #2.1
self.func = own_function
def __call__(self, *args, **kwargs): #2.2
print('"{}" was called with the following arguments'.format(self.func.__name__)) #2.3
print('\t{}\n\t{}\n'.format(args, kwargs)) #2.4
self.func(*args, **kwargs) #2.5
print('Decorator is still operating') #2.6
@SimpleDecorator
def combiner(*args, **kwargs):
print("\tHello from the decorated function; received arguments:", args, kwargs)
combiner('a', 'b', exec='yes') #1
# "combiner" was called with the following arguments #2.3
# ('a', 'b') #2.4
# {'exec': 'yes'}
#
# Hello from the decorated function; received arguments: ('a', 'b') {'exec': 'yes'} #2.5
# Decorator is still operating
## Class decorator
# class decorator
def add_logging_and_repr(cls):
orig_init = cls.__init__
def __init__(self, *args, **kwargs):
print(f"Creating instance of {cls.__name__}")
orig_init(self, *args, **kwargs)
def __str__(self):
return f"{cls.__name__}({', '.join(f'{k}={v}' for k, v in vars(self).items())})"
cls.__init__ = __init__
cls.__str__ = __str__
return cls
@add_logging_and_repr
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p)
# Creating instance of Person
# Person(name=Alice, age=30)