-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtips.txt
More file actions
122 lines (87 loc) · 2.42 KB
/
tips.txt
File metadata and controls
122 lines (87 loc) · 2.42 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
Python tips from "Compiling to Python"
1. local names are faster for repeated use.
variable names in Python can be:
- local to a functionn
- global to a module
- builtin Python
names that are 'local to a function' are faster
to access than builtins.
Hence,
```python3
def func():
print(str(3))
to_str = str
print(to_str(3)) # faster
```
2. one of the best way of creating strings is from a
list of strings, and then joining them.
3. calling a method on an object is executed in two
steps e.g
```python3
result = []
result.append("hello")
result.append("dude")
```
i. **append** is fetched from the **result** object
ii. the value fetched is invoked as a function by
passing "hello" as its argument.
An optimization principle to shave off the time required
by the first step is:
```python3
result = []
result_append = result.append
result_append("hello")
result_append("dude")
```
4. **exec** is a Python builtin function. Here is how it
works:
```python3
python_source = """\
SEVENTEEN = 17
def three():
return 3
"""
global_namespace = {}
exec(python_source, global_namespace)
# global_namespace["SEVENTEEN"] return 17
```
5. Argument unpacking
`*contexts` argument in the function below denotes that
all postional arguments will be packed into a tuple and
passed in as `contexts`.
```python3
def template(text, *contexts):
context = {}
for c in contexts:
context.update(c)
return context
t = template("dude")
t = template("dude", {"lower":str.lower})
t = template("dude", {"lower":str.lower}, {"upper":str.upper})
```
6. Closure
These are functions that refer to variables outside of
theirself. Consider:
```python3
class CodeBuilder:
def __init__(self):
self.code = []
def add(self, line):
self.code.append(line+'\n')
code = CodeBuilder()
buf = []
def flush_output():
if len(buf) == 1:
code.add("single(%s)" % buf[0])
elif len(buf) > 1:
code.add("multiple(%s)" % ",".join(buf))
del buf[:] # delete the contents of :buf:
```
:func flush_output: is a closure as it accesses :buf:
and :code: which are defined outside its body.
The similitude of the code above is a micro-optimization
logic used in the code generation phase of a template
engine design.
Strings are added to :buf: and the
:func flush_output: will make an appropriate decision
based on the length of :buf: when it is called.