Chapter 2: Notes on “Dive Into Python” by Mark Pilgrim
April 22nd, 2009 | No Comments »Note: I’m currently in the process of learning Python. These are notes on “Dive Into Python” by Mark Pilgrim (also available online), an excellent book if you’re like me and learn by the “do first, understand later” method.
Declaring functions
def functionName(params):
Defining a function’s doc string
def functionName(params): """This is the explanation of the function, surrounded by triple quotes. Returns a string."""
Further reading on document strings:
- Python Enhancement Proposals (PEP) 257: Docstring Conventions
- PEP 8: Style Guide for Python Code
- Documentation Strings in Python Tutorial (2.5.2)
Import search path
When importing a module, python looks in several places as defined in sys.path:
>>> import sys
>>> sys.path
['C:\Python25\Lib\idlelib', 'C:\Python25\lib\site-packages\setuptools-0.6c7-py2.5.egg',
'C:\WINDOWS\system32\python25.zip', 'C:\Python25\DLLs', 'C:\Python25\lib',
'C:\Python25\lib\plat-win', 'C:\Python25\lib\lib-tk', 'C:\Python25',
'C:\Python25\lib\site-packages']
>>> sys
<module 'sys' (built-in)>
>>> sys.path.append('/my/new/path')
The last line illustrates how to add a path to look in.
Everything is an object
Everything is an object! Functions, modules, strings, lists, everything! Python objects are objects in the sense that they can be passed as an argument to a function or be assigned to variables.
As an example, all functions have a built-in attribute called __doc__, which you can access like this:
>>> print importedModule.functionName.__doc__ This is the explanation of the function, surrounded by triple quotes. Returns a string.
Further reading on objects:
- “Objects, values, and types” in the Python Reference Manual
- “Python Objects” on effbot.org
Indenting code
As a newbie to Python, the built-in syntax rules are particularly appealing to me.
There are no braces for functions, no semicolons to end a line; simply indent and a code block is defined (for if statements, functions, etc.). The only delimiter here is the colon”:”.
Further reading on indenting code:
Testing modules with if __name__
All modules have a built-in attribute __name__. The value of this attribute depends on how the module is being used; is it imported or run on its own?
- If the module is imported, __name__ equals the filename (without path, without file extension)
- If the module is run as a stand-alone program, the value of __name__ is a special default value, __main__
Why is this important? It means that you can embed a test suite in the module itself. In other words, it’s code that will only execute when running the module directly, not when it’s being imported. To do this, you would include the following in the module:
if __name__ == "__main__":
"""Insert test code here."""
Further reading on importing modules:
Leave a Reply