Python - Modules
- Standard Modules - Many/all of these are built in modules for example sys
name variable with name of current module
Define a module like this:
crunchy.pydef crusty(x): x = x += 1 for i in range(10): result += x * i return result def crab(x): # return Fibonacci series up to n x = x += 2 for i in range(50): result += x * i return result
Use the module like this:
import crunchy
crunchy.crusty(1000)
crunchy.crab(100)
crunchy.__name__
crusty = crunchy.crusty
crusty(45)
- Modules contain code that is executed when they are imported for the first time ( used for initialization ).
- They can also be run as a script.
-
Modules can import other modules
- They contain global variables:
- Global vars within the module but won’t clash with global variables from importing module/script.
- Accessible from scripts that import the module ( dot notation )
Import names directly into importing module’s name space:
from crunchy import crusty, crab
crab(500)
You can import anything that doesn’t start with _. This could result in name conflict and is frowned upon. Here is how you do it:
from crunchy import *
crab(500)
import module with different name:
import crunchy as cr
cr.crab(500)
Import fuction with different name:
from crunchy import crab as snipper
snipper(500)
If you want to reload a module that has been changed without restarting the interpreter:
import importlib;
importlib.reload(crunchy)
Run python module as a script:
python crunchy.py
Instructions to be run only when executed as a script ( great for testing ):
if __name__ == "__main__":
x = sys.argv[1]
crab(int(x))
Module Search Path
First search built-in modules:
sys.builtin_module_names
Then search in the directories listed here ( can be overwritten ):
sys.path
sys.path is initialized by:
- current script dir
- PYTHONPATH
- installation dependent default ( including site-package dir )
The current script dir is prioritized.
import sys
sys.path.append('/home/user1/my_libs')
Compiled Python files
Compiled version of each module is stored here:
__pycache__/module.version.pyc
-
.pyc files load faster but doesn’t run faster
-
module compileall - use to compile all modules in a dir
- module automatically recompiled if source modification time is more recent
- module recompiled and not stored if directly from the cli
- does not check cache if there is no source module
Compiled only distribution:
- compiled version needs to be in source dir
- source needs to not be there
For optimized compiled files:
-O | remove aserts |
-OO | remove aserts and doc strings |
dir() Function
Show names ( variables, functions, modules, etc. ) defined by a module as sorted list of strings:
import crunchy, sys
dir(crunchy)
dir(sys)
dir() # names currently defined
The dir() function does not list built-in names, use the following to show these:
import builtins
dir(builtins)