-
Notifications
You must be signed in to change notification settings - Fork 1
/
40_starargs.py
47 lines (29 loc) · 1.14 KB
/
40_starargs.py
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
import re
from functools import partial
def printf(fmt, *args):
pass
print(re.sub(r'%s', partial(next, iter(args)), fmt))
printf("A greeting: %s", 'hello')
printf("Two greetings: %s, %s", 'hello', 'hi')
printf("Three greetings: %s, %s, %s", 'hello', 'hi', 'hey')
printf("Two greetings: %s, %s", args=('hello', 'hi'))
def send_sms(message, *recipients):
print(f"Send a message to: {recipients}")
# 'star-arg' is 0..*:
send_sms("How's it going?")
# Send a message to: ()
send_sms("How's it going?", "447700900770")
# Send a message to: ('447700900770',)
# Call with positional arguments:
send_sms("How's it going?", "447700900770", "447700900771")
# Send a message to: ('447700900770', '447700900771')
"""
This doesn't work - recipients is **not** a parameter:
# Provide args explicitly:
>>> send_sms("How's it going?", recipients=("447700900770", "447700900771"))
Traceback (most recent call last):
File "40_starargs.py", line 17, in <module>
send_sms("How's it going?", recipients=("447700900770", "447700900771"))
TypeError: send_sms() got an unexpected keyword argument 'recipients'
"""
# 'recipients' is usually called 'args'