Modules
Python organizes everything into modules, which are used to separate namespaces. Modules can be organized into packages thus providing a tree structure of arbitrary depth. Python itself contains an extensive library of built-in modules (the standard library).
Creating and using a module¶
Module is basically created by saving a file. This module can then be executed directly (we are rather talking about a script) or, typically, the module is imported. This is done using the import
keyword. Once the module is imported, you can use its symbols (functions, classes, global variables, etc.).
This snippet creates a file thisisamodule.py
in the current directory. This will create a module thisisamodule
.
%%file thisisamodule.py
# -*- coding: utf-8 -*-
def foo():
print(u"Doing nothing")
return None
Now we can import this module ...
import thisisamodule
.. and call its function foo
.
thisisamodule.foo()
We can also import only some of the module's symbols using from ... import ...
. Let's import path
from the built-in module sys
, which is the list of directories in which Python looks for modules.
from sys import path
path
We can also rename modules or its symbols by ... import ... as ...
# renames sys to system
import sys as system
# renames sys.path to syspath
from sys import path as syspath
# let's try if system.path is identical to syspath
print(system.path is syspath)
We also import everything from a module using from ... import *
. This is only recommended in interactive use and only if you know what you're doing. Otherwise, we can easily rewrite other symbols.
Running module as a script¶
To use a module as a script (ie. by executing python file_name.py
, alternatively %run
in IPython), we must test the value of __name__
. This variable contains the name of the module; however, once it's executed as a script, it contains "__main__". Thus a module that does something when executed will contain someting like
def hello(how, whom):
print("{} {}!".format(how, whom))
if __name__ == "__main__":
hello("Hello", "user")
Packages¶
Single-level hierarchy of modules would surely not be soon enough so it is possible to organize modules into packages. A package is a directory with a file named __init__.py
. This file can even be empty. We then place the package's modules into this directory. To import these modules we use package_name.module_name
.
See more in documentation.
Comments
Comments powered by Disqus