Like most projects, you start with a question. The how, the why.
While browsing through Twitter for inspiration for today’s post, I stumbled on Ben’s tweet about a new python package he created which does some data science magic.
I've been working on new python bindings for NMSLIB (awesome approximate KNN lib).
— Ben Frederickson (@benfrederickson) May 25, 2017
Pleased with how its turning out: https://t.co/eqtkyoGUfJ
I am not familiar with what the package does or what it is for, but it got me thinking:
- How does one create a Python package?
I created R packages before, but never Python ones. The repo for this little project is found .
Minimal requirements
According to How to Create a Python Package by Python Central (2012), you need to:
- Create a directory and give it your package’s name
- Put your classes (and functions) in it
- Create a
__init__.py
file in that directory
Following these instructions, in my “sample-python-package” repository, I (1) created a “mypackage” directory, (2) put my “test1” class inside a script inside that directory, and (3) created a __init__.py
file containing the class I want to load at import.
Here is what my file structure look like:
-- sample-python-package
|-- mypackage
| |-- __init__.py
| |-- test1.py
Here is the content of “test1.py”:
class Test1:
def __init__(self):
''' Constructor for this class. '''
self.world = ['Earth', 'Mars']
def printHello(self):
for world in self.world:
print('Hello %s!' % world)
def printGoodbye(self):
for world in self.world:
print('Goodbye %s!' % world)
And here is the content of __init__.py
:
# from .<file-name-without-py> import <class>
from .test1 import Test1
Note: It seems leaving __init__.py
blank will not load the “Test1” class during import mypackage
.
Test case
To test that this minimal package works, on the command line (in the “sample-python-package” directory), I started a ipython
session, ran the following commands, and saw the expected outputs which means this is a python package!
import mypackage
t1 = mypackage.Test1()
t1.printHello()
#> Hello Earth!
#> Hello Mars!
Future work
Now that I have a minimal python package working, I want to:
- Enable
pip
installation - Enable continuous integration with Travis