Repository navigation
Expand file tree
/
Copy pathfunctions.py
More file actions
104 lines (63 loc) · 2.27 KB
/
Copy pathfunctions.py
File metadata and controls
104 lines (63 loc) · 2.27 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
# function with no parameters
def no_params() -> str:
return "Hello, world!"
print(no_params())
# function with parameters
def mandatory_params(x: any, y: any, z: any) -> str:
return f"{x=}, {y=}, {z=}"
a_variable = 42
print(mandatory_params("a string", a_variable, True))
# function with default values for parameters
from typing import Optional
def latitude_dms(
deg: float, min: float, sec: float = 0.0, dir: Optional[str] = None
) -> str:
if dir is None:
dir = "N"
return f"{deg:02.0f} {min + sec / 60:05.3f}{dir}"
print(latitude_dms(36, 51, 2.9, "N"))
print(latitude_dms(38, 58, dir="N"))
# keywords only functions
def kw_only(x: any, y: str = "defaultkw", *, a: bool, b: str = "only") -> str:
return f"{x=}, {y=}, {a=}, {b=}"
print(kw_only("x", a="a", b="b"))
# print(kw_only("x")) # will generate error
# print(kw_only("x", "y", "a")) # will generate error
# positional-only parameters function
def pos_only(x: any, y: str, /, z: Optional[any] = None) -> str:
return f"{x=}, {y=}, {z=}"
print(pos_only(2, "three"))
print(pos_only(2, "three", 3.14159))
# print(pos_only(x=2, y="three")) # will generate error
# Additional details on defaults
# Default arguments is evaluated once when the function
# is first created, not when it is evaluated.
def add_item(item: str, items: list[str] = []) -> list:
items.append(item)
return items
print(add_item("apple")) # Output ['apple']
print(add_item("banana")) # Output ['apple', 'banana']
# the same list items is being modified across multiple
# funciton calls. Instead of getting a new list each
# time, the previous item remain.
# the correct approach
def add_item(item: str, items: list[str] = None) -> list:
if items is None:
items = []
items.append(item)
return items
print(add_item("apple")) # Output ['apple']
print(add_item("banana")) # Output ['apple']
number = 5
def funky_function(x: int = number) -> str:
return f"{x=}, {number=}"
print(funky_function(42))
number = 5
print(funky_function())
def better_function(x: Optional[int] = None) -> str:
if x is None:
x = number
return f"better: {x=}, {number=}"
def better_function_2(x: Optional[int] = None) -> str:
x = number if x is None else x
return f"better: {x=}, {number=}"