Python Programming/Modules and how to use them

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: Source Documentation and Comments Index Next: Files

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 import the time module as t:

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. To do this, you can do a from-import. Note that a from-import would import the name directly into the global namespace, so when invoking the imported function, it is unnecessary (and wrong) to call the module again:

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()

it is possible to alias a name imported through from-import


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()
TODO

TODO
Describe how modules are searched

TODO

TODO
Describe relative import and absolute import and the evil of relative import

Previous: Source Documentation and Comments Index Next: Files