[Baypiggies] Discussion for newbies/beginner night talks

Shannon -jj Behrens jjinux at gmail.com
Sat Feb 10 05:42:04 CET 2007


#) Don't Import the World

When designing a module and considering what modules it will need to
import, consider what the hierarchy of modules will look like when
you're done. If your hierarchy has arrows going back towards the top,
something is wrong; circular imports are nightmarish. It's better to
have many small modules with a clean hierarchy of imports.

#) Embrace Truth According to Python

Consider the following:

>>> def truth(x):
...     if x is not None:             # Truth test 1.
...         print "Not none."
...     if x:                         # Truth test 2.
...         print "bool(x) is not False."
...
>>> truth(None)                       # Fails both tests.
>>> truth(True)                       # Passes both tests.
Not none.
bool(x) is not False.                 # Only passes test 1.
>>> truth([])
Not none.

Python has a very-rich understanding of "truth". if x is not None is
very simple and fast. if x is very smart and flexible. Both are
useful. Understand the difference and pick the right one for your
situation.

#) Embrace the Pythonic Approach to Interfaces

Python doesn't have interfaces in the same way Java and C++ do.
Instead, it has duck typing, "If it looks like a duck and quacks like
a duck, it's a duck!" Consider:

>>> def talk_to(obj):
...     obj.talk()
...
>>> class Dog:
...     def talk(self):
...         print "Woof!"
...
>>> class Cat:
...     def talk(self):
...         print "Meow!"
...
>>> talk_to(Dog())
Woof!
>>> talk_to(Cat())
Meow!

In Java, Dog and Cat would need to either subclass some parent class
or implement an interface. This is unnecessary in Python. Nonetheless,
it's still a good idea to at least document complicated interfaces. If
you insist on creating what C++ calls a "pure virtual" method, here's
how:

>>> class Talks:
...     def talk(self):
...         """Print something interesting."""
...         raise NotImplementedError
...
>>> class Dog(Talks):
...     pass
...
>>> Dog().talk()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in talk
NotImplementedError

Tools like Epydoc and PyChecker understand this NotImplementedError
idiom. Furthermore, it's a great opportunity to include some
documentation about the method.

#) Use the dict.get() Method

>>> d = {"a": 1}
>>> if d.has_key("a"):                # This is the hard way.
...     value = d["a"]
... else:
...     value = "default"
...
>>> print value
1
>>> print d.get("a", "default")       # This is the easy way.
1
>>> b = d.get("b")
>>> if b is None:
...     print "Oh, no!  No b!"
...
Oh, no!  No b!

#) Similarly, have a peek at: help({}.setdefault).

Happy Hacking!
-jj


More information about the Baypiggies mailing list