One of the big advantages of Python is its huge module library. If you have ever written some code in Python, it is very likely that you imported some module to make the coding (and your life) easier.
However, modules are no hocus-pocus, it is really easy to create your own ones!
Let’s recapitulate quickly how modules work
Here us a very trivial example of how to use modules in Python:
I wrote a short function “removeSymbols” to remove all non-letter characters from a string. Therefore I imported the module “string”, which has a variable “ascii_letters” that contains all ASCII letters, so I don’t have to write them out myself.
To call this variable in my “removeSymbols” function, I have to use the following notation: modulename.variable or modulename.function. In this case I use
Save, Copy, Import, Go!
Now, I have a function that uses the contents of an other module to remove any non-ASCII letter from an input string. Let’s assume I want to use this function frequently in future programs, and I don’t want to type or copy this code into each individual script.
Make sure you removed the “print” command, so the script only contains functions. In order to “import” your function(s) into other scripts now, all you have to do is to save this script as “somename.py” and copy it into the same folder as the program that imports your module. However, if you are planning to use the module more frequently, you might want to consider putting it into the main Python system path so you can import it from anywhere. But since the main Python system path is more intended for the modules that come with Python, it is recommended to put your modules into the “/site-packages” sub-folder, which is there for 3rd party packages (thanks to Nazarijo, who pointed it out in the comments).
After you placed your module file into the right location, you can simply type the name of the “somename.py” (I called it “tmp.py” in my example – type “import tmp”) and you are ready to go.
Usually, the main Python modules are located in this folder:
depending on which version of Python you are using.
The easiest way to find your Python repository is to simply open a new Python shell and use the “sys” module:
>>> import sys >>> sys.path
which will give you all the relevant Python repositories as an output. In my case
['', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python33.zip', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages']