Fix Python – How to write a Python module/package?


Asked By – yowmamasita

I’ve been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help.

What I have:

(Just want to be specific as possible) I have the virtualenv ready, it’s also up in github, the .gitignore file for python is there as well, plus, the requests library for interacting with the REST API. That’s it.

Here’s the current directory tree

├── bin
│   └── /the usual stuff/
├── include
│   └── /the usual stuff/
├── lib
│   └── python2.7
│       └── /the usual stuff/
├── local
│   └── /the usual stuff/

27 directories, 280 files

I don’t even know where to put the .py files, if I ever make one.

What I wanted to do:

Make a python module install-able with “pip install …”

If possible, I want a general step by step process on writing Python modules.

Now we will see solution for issue: How to write a Python module/package?


A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py

create then write the following function as its content:

def helloworld():
   print "hello"

Then you can import hello:

>>> import hello
>>> hello.helloworld()

To group many .py files put them in a folder. Any folder with an is considered a module by python and you can call them a package


You can go about with the import statement on your module the usual way.

For more information, see 6.4. Packages.

This question is answered By – Anuj

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0