What I learned from reading Dive into Python.

I recently started reading Dive into Python. I've been meaning to fill some gaps in my Python knowledge, since I've used the language for about ten years, but feel like I have just picked whatever parts I needed to do my work and don't have a very solid base.

I'll summarize some of the new things I learned from this book:

Chapter 2 (Your First Python Program)

  • sys.path contains the list of directories that Python uses to lookup module imports.
  • One use of the __name__ attribute is to write testing code. When a module is imported __name__ is the name of the module. When a module python file is executed from the command line __name__ is equal to __main__. Personally this feels like a bit of a hack to me, since you can use something like say Django's unit testing platform, but it might come handy sometime.

Chapter 3 (Native Datatypes)

  • Here's a cool trick mentioned in this chapter:
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)

Chapter 4 (The Power Of Introspection):

  • Some useful functions are mentioned: dir (try on a module or an object instance), callable, getattr, __doc__.

So you can do something interesting, like this:

class Sum:
  """Sums numbers"""
  member = 3

  def sum2(self, a, b):
    """Sum two numbers"""
    return a + b

  def sum3(self, a, b, c):
    """Sum three numbers"""
    return a + b + c


if __name__ == '__main__':
  methods = [f for f in dir(Sum) if callable(getattr(Sum, f))]
  docs = '\n'.join(["%s %s" % (f, getattr(Sum, f).__doc__) for f in methods])
  print docs

And run it:

$ python ./sum.py
sum2 Sum two numbers
sum3 Sum three numbers
  • The "and-or trick"
is_mammal = use_rpc and remote_check_is_mammal(animal) or DEFAULT_IS_MAMMAL

That's like ?: in C++. I think I did well with creating a good example here :).

Chapter 5 (Objects and Object-Orientation)

  • var1 is var2 checks for object identity. Here's a good stackoverflow article that gives examples.
  • You can change a class variable using self.__class__.variable_name = new_value.
  • You can create your own dictionary by inheriting from UserDict.
  • If you call x["hello"] = 3, this calls the __setitem__ method. There are other similar methods, like __getitem__, etc.

Chapter 6 (Exceptions and file handling)

  • You can use else in exceptions code. Like this:
class RPC:
  def remote_call(self):
    pass

def find_function(name):
  try:
    a = getattr(RPC, name)
  except AttributeError:
    print 'No such function.'
  else:
    print 'Function was found.'
  finally:
    print 'Enough lookups.'
    print

find_function('func')
find_function('remote_call')

Output:

python ./ex.py 
No such function.
Enough lookups.

Function was found.
Enough lookups.
  • When you open a file, you have a variety of functions and attributes on the file object, like seek, read, mode, name. For example, to see how big a file is you can just call f.seek(0, 2) to seek until the end and then f.tell() to output the number of bytes.
  • A class' module is accessible by calling ClassName.__module__. All imported modules are in the sys.modules dictionary. Example:
>>> from sum import Sum
>>> import sys
>>> sys.modules[Sum.__module__]
<module 'sum' from 'sum.py'>
>>> getattr(sys.modules[Sum.__module__], 'Sum')
<class sum.Sum at 0x109535a10>

Chapter 7 (Regular Expressions)

  • \\b matches a word boundary. This can be so useful.
  • Verbose regular expressions. Again, very useful. Example:
import re

raw_regex = r"""
  (\d{3})
  \D*
  (\d{3})
  \D*
  (\d{4})
"""

examples = [
  "4153125633",
  "415-312-5633",
  "415 312 5633",
  "work 415 312 5633",
  "(415) - 312 - 5633",
  "1 415 312 5633",
]

phone_re = re.compile(raw_regex, re.VERBOSE)

for example in examples:
  groups = phone_re.search(example).groups()
  assert groups == ('415', '312', '5633')

social