Home > python > Creating and importing a module

Creating and importing a module

If you have some functions that you use often, you can collect them in a module.


def f1(n):
    return n + 1

How to use it (use-mymodule.py):

#!/usr/bin/env python

import mymodule

print mymodule.f1(5)      # => 6
print mymodule.__name__   # => mymodule (note that .py is missing)

It is also possible to add some testing code to a module:


#!/usr/bin/env python

def f1(n):
    return n + 1

if __name__ == "__main__":
    number = 1977
    print f1(number)   # => 1978

Now, you can still import it like in use-mymodule.py, or you can launch it as if it were a standalone script. In the latter case the test suite will be executed. If you import it, the test suite is not executed. A test suite is a good practice to be sure that the module is working as expected.

Categories: python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: