220e3bd423e4e9b23f984e44fdfa3b73504e0374
[python-guide.git] / docs / writing / structure.rst
1 Structuring Your Project
2 ========================
3
4 Structuring your project properly is extremely important.
5
6 .. todo:: Fill in "Structuring Your Project" stub
7
8 Structure is Key
9 ----------------
10
11 Thanks to the way imports and modules are handled in Python, it is
12 relatively easy to structure a Python project. Easy, here, means
13 that you do not have many constraints and that the module
14 importing model is easy to grasp. Therefore, you are left with the
15 pure architectural task of crafting the different parts of your
16 project and their interactions.
17
18 Easy structuring of a project means it is also easy
19 to do it poorly. Some signs of a poorly structured project
20 include:
21
22 - Multiple and messy circular dependencies: If your classes
23   Table and Chair in furn.py need to import Carpenter from workers.py
24   to answer a question such as table.isdoneby(),
25   and if conversely the class Carpenter needs to import Table and Chair,
26   to answer the question carpenter.whatdo(), then you
27   have a circular dependency. In this case you will have to resort to
28   fragile hacks such has using import statements inside
29   methods or functions.
30
31 - Hidden coupling: Each and every change in Table's implementation
32   breaks 20 tests in unrelated test cases because it breaks Carpenter's code,
33   which requires very careful surgery to adapt the change. This means
34   you have too many assumptions about Table in Carpenter's code or the
35   reverse.
36
37 - Heavy usage of global state or context: Instead of explicitly
38   passing ``(height, width, type, wood)`` to each other, Table
39   and Carpenter rely on global variables that can be modified
40   and are modified on the fly by different agents. You need to
41   scrutinize all access to these global variables to understand why
42   a rectangular table became a square, and discover that remote
43   template code is also modifying this context, messing with
44   table dimensions.
45
46 - Spaghetti code: Multiple pages of nested if clauses and for loops
47   with a lot of copy-pasted procedural code and no
48   proper segmentation are known as spaghetti code. Python's 
49   meaningful indentation (one of its most controversial features) make
50   it very hard to maintain this kind of code. So the good news is that
51   you might not see too much of it.
52
53 - Ravioli code is more likely in Python: It consists of hundreds of
54   similar little pieces of logic, often classes or objects, without
55   proper structure. If you never can remember if you have to use
56   FurnitureTable, AssetTable or Table, or even TableNew for your
57   task at hand, you might be swimming in ravioli code.
58
59
60 Modules
61 -------
62
63 Python modules are one of the main abstraction layers available and probably the
64 most natural one. Abstraction layers allow separating code into parts holding
65 related data and functionality.
66
67 For example, a layer of a project can handle interfacing with user actions,
68 while another would handle low-level manipulation of data. The most natural way
69 to separate these two layers is to regroup all interfacing functionality
70 in one file, and all low-level operations in another file. In this case,
71 the interface file needs to import the low-level file. This is done with the
72 `import` and `from ... import` statements.
73
74 As soon as you use `import` statements you use modules. These can be either built-in
75 modules such as `os` and `sys`, third-party modules you have installed in your
76 environment, or your project's internal modules.
77
78 Nothing special is required for a Python file to be a module, but the import
79 mechanism needs to be understood in order to use this concept properly and avoid
80 some issues.
81
82 Concretely, the `import modu` statement will look for the proper file, which is
83 `modu.py` in the same directory as the caller if it exists.  If it is not
84 found, the Python interpreter will search for `modu.py` in the "path"
85 recursively and raise an ImportError exception if it is not found.
86
87 Once `modu.py` is found, the Python interpreter will execute the module in an
88 isolated scope. Any top-level statement in `modu.py` will be executed,
89 including other imports if any. Function and class definitions are stored in
90 the module's dictionary.
91
92 Then, the module's variables, functions, and classes will be available to the caller
93 through the module's namespace, a central concept in programming that is
94 particularly helpful and powerful in Python.
95
96 In many languages, an `include file` directive is used by the preprocessor to
97 take all code found in the file and 'copy' it into the caller's code. It is
98 different in Python: the included code is isolated in a module namespace, which
99 means that you generally don't have to worry that the included code could have
100 unwanted effects, e.g. override an existing function with the same name.
101
102 It is possible to simulate the more standard behavior by using a special syntax
103 of the import statement: `from modu import *`. This is generally considered bad
104 practice. **Using `import *` makes code harder to read and makes dependencies less
105 compartmentalized**.
106
107 Using `from modu import func` is a way to pinpoint the function you want to
108 import and put it in the global namespace. While much less harmful than `import
109 *` because it shows explicitly what is imported in the global namespace, its
110 advantage over a simpler `import modu` is only that it will save some typing.
111
112 **Very bad**
113
114 .. code-block:: python
115
116     [...]
117     from modu import *
118     [...]
119     x = sqrt(4)  # Is sqrt part of modu? A builtin? Defined above?
120
121 **Better**
122
123 .. code-block:: python
124
125     from modu import sqrt
126     [...]
127     x = sqrt(4)  # sqrt may be part of modu, if not redefined in between
128
129 **Best**
130
131 .. code-block:: python
132
133     import modu
134     [...]
135     x = modu.sqrt(4)  # sqrt is visibly part of modu's namespace
136
137 As said in the section about style, readability is one of the main features of
138 Python. Readability means to avoid useless boilerplate text and clutter,
139 therefore some efforts are spent trying to achieve a certain level of brevity.
140 But terseness and obscurity are the limits where brevity should stop. Being
141 able to tell immediately where a class or function comes from, as in the
142 `modu.func` idiom, greatly improves code readability and understandability in
143 all but the simplest single file projects.
144
145
146 Packages
147 --------
148
149 Python provides a very straightforward packaging system, which is simply an
150 extension of the module mechanism to a directory.
151
152 Any directory with an __init__.py file is considered a Python package. The
153 different modules in the package are imported in a similar manner as plain
154 modules, but with a special behavior for the __init__.py file, which is used to
155 gather all package-wide definitions.
156
157 A file modu.py in the directory pack/ is imported with the statement `import
158 pack.modu`. This statement will look for an __init__.py file in `pack`, execute
159 all of its top-level statements. Then it will look for a file `pack/modu.py` and
160 execute all of its top-level statements. After these operations, any variable,
161 function, or class defined in modu.py is available in the pack.modu namespace.
162
163 A commonly seen issue is to add too much code to __init__.py
164 files. When the project complexity grows, there may be sub-packages and
165 sub-sub-packages in a deep directory structure, and then, importing a single item
166 from a sub-sub-package will require executing all __init__.py files met while
167 traversing the tree.
168
169 Leaving an __init__.py file empty is considered normal and even a good practice,
170 if the package's modules and sub-packages do not need to share any code.
171
172 Lastly, a convenient syntax is available for importing deeply nested packages:
173 `import very.deep.module as mod`. This allows you to use `mod` in place of the verbose
174 repetition of `very.deep.module`.
175
176 Object-oriented programming
177 ---------------------------
178
179 Python is sometimes described as an object-oriented programming language. This
180 can be somewhat misleading and needs to be clarified.
181
182 In Python, everything is an object, and can be handled as such. This is what is
183 meant when we say that, for example, functions are first-class objects.
184 Functions, classes, strings, and even types are objects in Python: like any
185 objects, they have a type, they can be passed as function arguments, they may
186 have methods and properties. In this understanding, Python is an
187 object-oriented language.
188
189 However, unlike Java, Python does not impose object-oriented programming as the
190 main programming paradigm. It is perfectly viable for a Python project to not
191 be object-oriented, i.e. to use no or very few class definitions, class
192 inheritance, or any other mechanisms that are specific to object-oriented
193 programming.
194
195 Moreover, as seen in the modules_ section, the way Python handles modules and
196 namespaces gives the developer a natural way to ensure the
197 encapsulation and separation of abstraction layers, both being the most common
198 reasons to use object-orientation. Therefore, Python programmers have more
199 latitude to not use object-orientation, when it is not required by the business
200 model.
201
202 There are some reasons to avoid unnecessary object-orientation. Defining
203 custom classes is useful when we want to glue together some state and some
204 functionality. The problem, as pointed out by the discussions about functional
205 programming, comes from the "state" part of the equation.
206
207 In some architectures, typically web applications, multiple instances of Python
208 processes are spawned to respond to external requests that can
209 happen at the same time. In this case, holding some state into instantiated
210 objects, which means keeping some static information about the world, is prone
211 to concurrency problems or race-conditions. Sometimes, between the initialization of
212 the state of an object (usually done with the __init__() method) and the actual use
213 of the object state through one of its methods, the world may have changed, and
214 the retained state may be outdated. For example, a request may load an item in
215 memory and mark it as read by a user. If another request requires the deletion
216 of this item at the same, it may happen that the deletion actually occurs after
217 the first process loaded the item, and then we have to mark as read a deleted
218 object.
219
220 This and other issues led to the idea that using stateless functions is a
221 better programming paradigm.
222
223 Another way to say the same thing is to suggest using functions and procedures
224 with as few implicit contexts and side-effects as possible. A function's
225 implicit context is made up of any of the global variables or items in the persistence layer
226 that are accessed from within the function. Side-effects are the changes that a function makes
227 to it's implicit context. If a function saves or deletes data in a global variable or
228 in the persistence layer, it is said to have a side-effect.
229
230 Carefully isolating functions with context and side-effects from functions with
231 logic (called pure functions) allow the following benefits:
232
233 - Pure functions are more likely to be deterministic: given a fixed input,
234   the output will always be the same.
235
236 - Pure functions are much easier to change or replace if they need to
237   be refactored or optimized.
238
239 - Pure functions are easier to test with unit-tests: There is less
240   need for complex context setup and data cleaning afterwards.
241
242 - Pure functions are easier to manipulate, decorate_, and pass-around.
243
244 In summary, pure functions, without any context or side-effects, are more
245 efficient building blocks than classes and objects for some architectures.
246
247 Obviously, object-orientation is useful and even necessary in many cases, for
248 example when developing graphical desktop applications or games, where the
249 things that are manipulated (windows, buttons, avatars, vehicles) have a
250 relatively long life of their own in the computer's memory.
251
252
253 Decorators
254 ----------
255
256 The Python language provides a simple yet powerful syntax called 'decorators'.
257 A decorator is a function or a class that wraps (or decorate) a function
258 or a method. The 'decorated' function or method will replace the original
259 'undecorated' function or method. Because functions are first-class objects
260 in Python, it can be done 'manually', but using the @decorator syntax is
261 clearer and thus preferred.
262
263 .. code-block:: python
264
265     def foo():
266         # do something
267
268     def decorator(func):
269         # manipulate func
270         return func
271
272     foo = decorator(foo)  # Manually decorate
273
274     @decorator
275     def bar():
276         # Do something
277     # bar() is decorated
278
279 Using this mechanism is useful for separating concerns and avoiding
280 external un-related logic 'polluting' the core logic of the function
281 or method. A good example of a piece of functionality that is better handled
282 with decoration is memoization or caching: you want to store the results of an
283 expensive function in a table and use them directly instead of recomputing
284 them when they have already been computed. This is clearly not part
285 of the function logic.
286
287 Dynamic typing
288 --------------
289
290 Python is said to be dynamically typed, which means that variables
291 do not have a fixed type. In fact, in Python, variables are very
292 different from what they are in many other languages, specifically
293 strongly-typed languages. Variables are not a segment of the computer's
294 memory where some value is written, they are 'tags' or 'names' pointing
295 to objects. It is therefore possible for the variable 'a' to be set to
296 the value 1, then to the value 'a string', then to a function.
297
298 The dynamic typing of Python is often considered to be a weakness, and indeed
299 it can lead to complexities and hard-to-debug code. Something
300 named 'a' can be set to many different things, and the developer or the
301 maintainer needs to track this name in the code to make sure it has not
302 been set to a completely unrelated object.
303
304 Some guidelines help to avoid this issue:
305
306 - Avoid using variables for different things.
307
308 **Bad**
309
310 .. code-block:: python
311
312     a = 1
313     a = 'a string'
314     def a():
315         pass  # Do something
316
317 **Good**
318
319 .. code-block:: python
320
321     count = 1
322     msg = 'a string'
323     def func()
324         pass  # Do something
325
326 Using short functions or methods helps reduce the risk
327 of using the same name for two unrelated things.
328
329 It is better to use different names even for things that are related,
330 when they have a different type:
331
332 **Bad**
333
334 .. code-block:: python
335
336     items = 'a b c d'  # This is a string...
337     items = items.split(' ')  # ...becoming a list
338     items = set(items)  # ...and then a set
339
340 There is no efficiency gain when reusing names: the assignments
341 will have to create new objects anyway. However, when the complexity
342 grows and each assignment is separated by other lines of code, including
343 'if' branches and loops, it becomes harder to ascertain what a given
344 variable's type is.
345
346 Some coding practices, like functional programming, recommend never reassigning a variable.
347 In Java this is done with the `final` keyword. Python does not have a `final` keyword
348 and it would be against its philosophy anyway. However, it may be a good
349 discipline to avoid assigning to a variable more than once, and it helps
350 in grasping the concept of mutable and immutable types.
351
352 Mutable and immutable types
353 ---------------------------
354
355 Python has two kinds of built-in or user-defined types.
356
357 Mutable types are those that allow in-place modification
358 of the content. Typical mutables are lists and dictionaries:
359 All lists have mutating methods, like append() or pop(), and
360 can be modified in place. The same goes for dictionaries.
361
362 Immutable types provide no method for changing their content.
363 For instance, the variable x set to the integer 6 has no "increment" method. If you
364 want to compute x + 1, you have to create another integer and give it
365 a name.
366
367 .. code-block:: python
368
369     my_list = [1, 2, 3]
370     my_list[0] = 4
371     print my_list  # [4, 2, 3] <- The same list as changed
372
373     x = 6
374     x = x + 1  # The new x is another object
375
376 One consequence of this difference in behavior is that mutable
377 types are not "stable", and therefore cannot be used as dictionary
378 keys.
379
380 Using properly mutable types for things that are mutable in nature
381 and immutable types for things that are fixed in nature
382 helps to clarify the intent of the code.
383
384 For example, the immutable equivalent of a list is the tuple, created
385 with ``(1, 2)``. This tuple is a pair that cannot be changed in-place,
386 and can be used as a key for a dictionary.
387
388 One peculiarity of Python that can surprise beginners is that
389 strings are immutable. This means that when constructing a string from
390 its parts, it is much more efficient to accumulate the parts in a list,
391 which is mutable, and then glue ('join') the parts together when the
392 full string is needed.
393
394 Vendorizing Dependencies
395 ------------------------
396
397
398
399 Runners
400 -------
401
402
403 Further Reading
404 ---------------