Python Scientific Lecture Notes, Release 2012.3 (Euroscipy 2012)
Python Scientific Lecture Notes, Release 2012.3 (Euroscipy 2012)
3 (EuroScipy 2012)
In [1]: import os
In [2]: os
Out[2]: <module ’os’ from ’ / usr / lib / python2.6 / os.pyc ’ >
In [3]: os.listdir(’.’)
Out[3]:
[’conf.py’,
’basic_types.rst’,
’control_flow.rst’,
’functions.rst’,
’python_language.rst’,
’reusing.rst’,
’file_io.rst’,
’exceptions.rst’,
’workflow.rst’,
’index.rst’]
And also:
In [4]: from os import listdir
Importing shorthands:
In [5]: import numpy as np
Warning:
from os import *
Do not do it.
• Makes the code harder to read and understand: where do symbols come from?
• Makes it impossible to guess the functionality by the context and the name (hint: os.name is the name
of the OS), and to profit usefully from tab completion.
• Restricts the variable names you can use: os.name might override name, or vise-versa.
• Creates possible name clashes between modules.
• Makes the code impossible to statically check for undefined symbols.
Modules are thus a good way to organize code in a hierarchical way. Actually, all the scientific computing tools
we are going to use are modules:
>>> import numpy as np # data arrays
>>> np.linspace(0, 10, 6)
array([ 0., 2., 4., 6., 8., 10.])
>>> import scipy # scientific computing
If we want to write larger and better organized programs (compared to simple scripts), where some objects are
defined, (variables, functions, classes) and that we want to reuse several times, we have to create our own modules.
Let us create a module demo contained in the file demo.py: