<< >>

diveintopython.org |

Python for experienced programmers

## Appendix C. Tips and tricks

Chapter 1. Getting To Know Python

- 1.1. Diving in

  In the Python IDE on Windows, you can run a module with File->Run… (Ctrl-R). Output is displayed in the interactive window.

  In the Python IDE on MacOS, you can run a module with Python->Run window… (Cmd-R), but there is an important option you must set first. Open the module in the IDE, pop up the module's options menu by clicking the black triangle in the upper-right corner of the window, and make sure “Run as __main__” is checked. This setting is saved with the module, so you only have to do this once per module.

  On UNIX-compatible systems (including MacOS X), you can run a module from the command line: `python `odbchelper.py``

- 1.2. Declaring functions

  Automatic datatyping is a double-edged sword. It's convenient, and it can be extremely powerful. But it places an additional burden on you to understand when and how Python coerces data into different types.

- 1.3. Documenting functions

  Many Python IDEs use the `doc string` to provide context-sensitive documentation, so that when you type a function name, its `doc string` appears as a tooltip. This can be incredibly helpful, but it's only as good as the `doc string`s you write.

- 1.6. Testing modules

  On MacPython, there is an additional step to make the `if` `__name__` trick work. Pop up the module's options menu by clicking the black triangle in the upper-right corner of the window, and make sure Run as __main__ is checked.

- 1.7. Dictionaries 101

  Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; they are simply unordered. This is an important distinction which will annoy you when you want to access the elements of a dictionary in a specific, repeatable order (like alphabetical order by key). There are ways of doing this, they're just not built into the dictionary.

- 1.8. Lists 101

  There is no boolean datatype in Python. In a boolean context (like an `if` statement), `0` is false and all other numbers are true. This extends to other datatypes, too. An empty string (`""`), an empty list (`[]`), and an empty dictionary (`{}`) are all false; all other strings, lists, and dictionaries are true.

- 1.9. Tuples 101

  Tuples can be converted into lists, and vice-versa. The built-in `tuple` function takes a list and returns a tuple with the same elements, and the `list` function takes a tuple and returns a list. In effect, `tuple` freezes a list, and `list` thaws a tuple.

- 1.10. Defining variables

  When a command is split among several lines with the line continuation marker (“`\`”), the continued lines can be indented in any manner; Python's normally stringent indentation rules do not apply. If your Python IDE auto-indents the continued line, you should probably accept its default unless you have a burning reason not to.

  Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character (“`\`”). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style.

- 1.13. Joining lists and splitting strings

  `join` only works on lists of strings; it does not do any type coercion. `join`ing a list that has one or more non-string elements will raise an exception.

  `string.`split`(delimiter, 1)` is a useful technique when you want to search a string for a substring and then work with everything before the substring (which ends up in the first element of the returned list) and everything after it (which ends up in the second element).

Chapter 2. The Power Of Introspection

- 2.3. Optional and named arguments

  The only thing you have to do to call a function is specify a value (somehow) for each required argument; the manner and order in which you do that is up to you.

- 2.4. type, str, dir, and other built-in functions

  Python comes with excellent reference manuals, which you should peruse thoroughly to learn all the modules Python has to offer. But whereas in most languages you would find yourself referring back to the manuals (or man pages, or, God help you, MSDN) to remind yourself how to use these modules, Python is largely self-documenting.

- 2.7. The and-or trick

  The `and-or` trick, `bool and `a` or `b``, will not work like the C expression `bool ? `a` : `b`` when `a` is false.

  A conscientous programmer could encapsulate the `and-or` trick into a function:
      def choose(bool, a, b):
          return (bool and [a] or [b])[0]

- 2.8. Using lambda functions

  `lambda` functions are a matter of style. Using them is never required; anywhere you could use them, you could define a separate normal function and use that instead. I use them in places where I want to encapsulate specific, non-reusable code without littering my code with a lot of little one-line functions.

Chapter 3. An Object-Oriented Framework

- 3.2. Defining classes

  `__init__` methods are optional, but when you define one, you must remember to explicitly call the ancestor's `__init__` method. This is more generally true: whenever a descendant wants to extend the behavior of the ancestor, the descendant method must explicitly call the ancestor method at the proper time, with the proper arguments.

- 3.4. UserDict: a wrapper class

  In the Python IDE on Windows, you can quickly open any module in your library path with File->Locate… (Ctrl-L).

  Always assign an initial value to all of a class's data attributes in the `__init__` method. It will save you hours of debugging later.

- 3.5. Special class methods

  When accessing data attributes within a class, you need to qualify the attribute name: `self.attribute`. When calling other methods within a class, you need to qualify the method name: `self.method`.

- 3.6. Advanced special class methods

  While other object-oriented languages only let you define the physical model of an object (“this object has a `GetLength` method”), special class methods like `__len__` allow you to define the logical model of an object (“this object has a length”).

- 3.8. Private functions

  If the name of a Python function, class method, or attribute starts with (but doesn't end with) two underscores, it's private; everything else is public.

  In Python, all special methods (like `__setitem__`) and built-in attributes (like `__doc__`) follow a standard naming convention: they both start with and end with two underscores. Don't name your own methods and attributes this way; it will only confuse you (and others) later.

  Python has no concept of protected class methods (accessible only in their own class and descendant classes). Class methods are either private (accessible only in their own class) or public (accessible from anywhere).

- 3.12. Assigning multiple values at once

  Whenever possible, you should use the functions in `os` and `os.path` for file, directory, and path manipulations. These modules are wrappers for platform-specific modules, so functions like `os.path.split` work on UNIX, Windows, MacOS, and any other supported Python platform.

  Using multi-variable assignment is never strictly necessary. It's a convenient shortcut, and it can make your code more readable, especially when dealing with dictionaries (through the `items` method). But if you find yourself putting your code through contortions to get data in the right format just so you can assign two variables at once, it's probably not worth it.

« A 5-minute review | List of examples »