2.6. Organizing Python Source Code

2.6.1. Functions

The rules for when Python uses call by value or call by reference to pass parameters to functions is the same as they are in Java. The core built-in data types (int, long, float and string) are all immutable data types and when they are passed to either a function or class methods, call by value is used. When mutable objects are used with class methods, call by reference is used.

>>> # Call by value example
>>> def test(x):
...     x = x + 2
>>> z = 2
>>> test(z)
>>> print z

>>> # Another call by value example
>>> def stest(st):
...     st = st + "Hello"
>>> s = "joe"
>>> stest(s)
>>> print s

>>> # Setup for a call by reference example
>>> class ctest:
...     def __init__(self, n):
...         self.n = n
>>> def c1test(n):
...     n.n = n.n + 2
>>> x = ctest(5)
>>> x.n
>>> # Now, x is passed by reference to c1test function.
>>> c1test(x)
>>> x.n

2.6.2. Classes

The syntax for defining a Python class is as follows:

Class classname(base_class):
    optional documentation string

    static variable declarations

    method declarations
  • Method declarations are just function definitions.
  • The __init__(self, other_args) method is initialization code, not a constructor – subtle point. A __new__() method may also be declared, which is a constructor. You will not need the __new__() method for this class.
  • Use self.var_name to reference any class data variables.

2.6.3. Modules

  • Python features which are not loaded, by default can brought into a Python by importing a module.
  • Module foo would be imported using a import foo statement. This loads the module and evaluates it’s code. Classes and functions from the module are then called with the module name prefixed: x = foo.bar().
  • If we just want to import the bar() function, we could use the following syntax: from foo import bar. Now, we could call the bar() as simply: x = bar().


  • Upon importing a module, the code in the module is evaluated. This means that classes and functions become available since Python knows about them only after they are evaluated. But this also means that any global statements get executed when they are imported.

  • In simple Python scripts, we often put the code at the global level. This is fine, if the code will never be imported. A better, long term strategy is to put most, or all of the code inside functions and classes and add a statement such as the following at the end of the file:

    if __name__ == '__main__':

    The above statements execute a function called main if the program is run as a stand alone program, but not if it is imported. The global name: __name__ is a built-in name, which is set to ‘__main__’ when the file is executed directly by Python, but is the name of the module when it is imported.