A while ago I was tasked with packaging up a bunch of my functions and at the time I was like no, no, I ain’t doing that, I ain’t spending hours figuring it out, I have to keep going. 6 months later I needed to do a similar analysis and I was fucked because I had to re-code a bunch of the same shit again. I then said, “never again.” So, I packaged it up.
This by no means is best or maybe the most proper way to do it, but it’s simple and it works.
First off, let’s define what a package is. A package is a collection of modules and modules are a collection of functions. Hence, why packages are so useful; if we can cluster all of our hard-thought functions into a nice bundle, we can call them at any time, from anywhere. Sweet.
def add(x, y): resultAdd = x + y return resultAdd def multiply(x, y): resultMult = x + y return resultMult
If we now put those two functions in a file, say, called myModule.py, you’d have a module. And as long as the module file is in your working folder then you can call it. However, most often than not we will need to call our functions from somewhere else.
Now create a folder, called myPackage. Move myModule.py to it.
The main characteristic of a package is that it contains an __init__.py file. This file will tell python that working folder is a package. Inside myPackage/, create an __init__.py file that includes a call to your methods like so:
from myModule import add from myModule import multiply
Here’s how your working folder should look like right now:
myPackage/
|---- __init__.py
|---- myModule.py
To install this package in your machine and your machine only, run the following line inside the working folder,
python setup.py install
And that is it, now you can call your modules from anywhere in your machine. Yaaas Kween!!!!
import myPackage as mp someVar = mp.add(arg1, arg2)
Be sure to add readme file so 6 months you know why and what the fuck you wrote.
Happy Coding!
One thought on “Easy Way to Write a Python Package”