Python Programming/Modules and how to use them
Modules are libraries that can be called from other scripts. For example, a popular module is the time
module. You can call it using:
import time
Then, create a new python file, you can name it anything (except time.py, since it'd mess up python's module importing, you'll see why later):
import time def main(): # define the variable 'current_time' as a tuple of time.localtime() current_time = time.localtime() print(current_time) # print the tuple # if the year is 2009 (first value in the current_time tuple) if current_time[0] == 2009: print('The year is 2009') # print the year if __name__ == '__main__': # if the function is the main function ... main() # ...call it
Modules can be called in a various number of ways. For example, we could alias the time module with the reserved word as:
import time as t # import the time module and call it 't' def main(): current_time = t.localtime() print(current_time) if current_time[0] == 2009: print('The year is 2009') if __name__ == '__main__': main()
It is not necessary to import the whole module. If you only need a certain function or class, use from-import. Note that a from-import would import the name directly into the global namespace. In other words, when invoking the imported function, don't include the module's name:
from time import localtime #1 def main(): current_time = localtime() #2 print(current_time) if current_time[0] == 2009: print 'The year is 2009' if __name__ == '__main__': main()
The from-import form can also be aliased:
from time import localtime as lt def main(): current_time = lt() print(current_time) if current_time[0] == 2009: print('The year is 2009') if __name__ == '__main__': main()
People who do test-first programming or perform regression testing write a main() function in every Python module, and a main() method in every Java class, to run automated tests. When a person executes the file directly, the main() function executes and runs the automated tests for that file. When a person executes some other Python file that in turn imports many other Python files, only one main() function is executed -- the main() function of the directly-executed file.
Summary[edit]
Every module can be easily searched or imported. A module is just an ordinary file in the form <filename>.py
. A module called mymodule.py
can be imported into main.py
by inserting import mymodule.py
at the top of main.py
. After importing mymodule.py
, you can modify and use the module's functions and variables in main.py. To access them, use the form mymodule.myfunction()
. To access any documentation, use the form pydoc mymodule
.