codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Creating Local Python Packages with __init__.py

Packages for code reuse and distribution

Citizen Upgrade
codeburst
Published in
6 min readDec 15, 2020

Unorganized packages
Photo by boris misevic on Unsplash

When it comes to choosing a coding language for a project, I generally select from a few options available to me at work. If it’s only a few lines, I tend to use Bash. If it’s going to require software architecting, I tend to use C++ or Java (I really want to get into Rust, but there’s very limited support for that at my current job). For everything in between, I use Python.

Python is a perfect “intermediate” language for those quick one-off scripts, it works for larger projects, but my small Python scripts tend to grow over time. I need my code to be relatively portable, but building everything into its own module as the code grows leads to duplication, unnecessary bloat, and even code rot.

Virtually every language has a way to build and load common functionality. In Python, the feature is known as a “package”. Packages can be built for large distributions, but here I want to talk about creating simple package directories that you can use to promote code reuse among your own scripts or when you need to send a tarball of a script off to a friend or co-worker. Those don’t need to be as rigidly defined.

I find myself frequently looking up the options in __init__.py and confusing the options. Here’s a quick primer in how to build packages you can send off with your scripts. These should work across most versions of Python (tested in 2.7 and 3.6).

I’m going to focus on the __init__.py packaging and not namespace packaging here. I find this method to be the easiest to use and useful just about everywhere in the size project I tend to work in. I’m also not going to talk about setup.py and what else can go in __init__.py (eg: version, author, etc). For small scripts that just need code reuse, I generally don’t bother. If for no other reason than I don’t need my coworkers hunting me down to fix code they borrowed from me in the first place!

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Citizen Upgrade

Upgrade your world. Upgrade your life. A community of experts covering technology, society, and personal development. Visit us at: www.citizenupgrade.com

No responses yet

Write a response