-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc
More file actions
executable file
·64 lines (51 loc) · 1.71 KB
/
Copy pathfunc
File metadata and controls
executable file
·64 lines (51 loc) · 1.71 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
#!/usr/bin/env python3
# / indicates end of postional args
# * indicates end of args that can be keyword or positional
# (eg, a cannot be passed by keyword, c *must* be passed by keyword)
def foo(a: str = 'default a', /, b: str = 'default b', *, c=['default c'], **kwargs):
if 'verbose' in kwargs:
print("a:", a, end=': ')
print("b:", b, end=': ')
print("c:", c)
c.append(a) # Modifies/mutates the default value for subsequent calls
bar = foo
assert foo.__name__ == 'foo'
assert bar.__name__ == 'foo'
assert(foo.__annotations__ == {'b': str, 'a': str})
foo(1, verbose=1)
foo(2, 5, verbose=1)
foo(3, b=6, verbose=1)
a = ['foo']
print(f"Before call: a = {a}", end=', ')
foo(4, c=a, quiet=True) # appends 4 to a
print(f"After, a = {a}")
foo(5)
try:
foo(a=5, b=6, c=7) # Error: a cannot be passed by keyword
except Exception as e:
print(f'caught calling foo with 3 kwargs: {e}')
foo(5, 6, c=[9]) # okay
foo(5, b=6, c=[9]) # okay
try: foo(5, 6, [9]) # Error: cannot pass c by position
except Exception as e:
print(f'caught calling foo with 3 positional args {e}')
def kwdict(a, foo=1, bar=2, **kwargs):
print(f'a = {a}')
print(f'foo = {foo}')
print(f'bar = {bar}')
print('baz = {}'.format(kwargs['baz']))
try:
kwdict(5)
except Exception as e:
print('baz not defined caught:', e)
a = {'a': 5, 'foo': 'foovalue', 'bar': 'bazvahlue'}
kwdict(baz='unp', **a)
a['baz'] = 'baz added'
kwdict(**a)
# If function definition does not contain / to indicate
# end of postional args, all args are keyword
def bar(a, b = 'def b'):
return f'a={a}, b={b}'
assert(bar(b = 5, a = 2) == 'a=2, b=5')
assert(bar(**{"b": 5, "a": 2}) == 'a=2, b=5')
assert(bar(*[1,2]) == 'a=1, b=2')