Skip to content

Instantly share code, notes, and snippets.

@kms70847
Last active December 17, 2019 18:34
Show Gist options
  • Save kms70847/2df51c3a2d9953c47797b0b9798bb03b to your computer and use it in GitHub Desktop.
Save kms70847/2df51c3a2d9953c47797b0b9798bb03b to your computer and use it in GitHub Desktop.
The Simplest Possible Way To Make A Python File Into A Package That's Importable From Anywhere
The Simplest Possible Way To Make A Python File Into A Package That's Importable From Anywhere
~~~ A Guide For (And By) the Incurably Befuddled ~~~
==============================================================================================
SCENARIO: while writing a one-shot project, you construct a module named LovelyCoconut.py.
#main.py
import LovelyCoconut
LovelyCoconut.bang_halves_together()
#LovelyCoconut.py
def bang_halves_together():
print("Clip clop clip clop")
Obviously, LovelyCoconut is a very useful module and you would like to be able to import it no matter what directory you are in. You want it to be a full fledged PACKAGE. But how!?
========================================================================
HOW:
LovelyCoconut.py is useless to us as an ordinary module. This ugly caterpillar must become a beautiful butterfly.
1) Create a new directory with the following structure:
LovelyCoconut\ <- The name of your project.
setup.py <- Empty for now. See step 2.
LovelyCoconut\ <- The name that you want to be able to import.
__init__.py <- Empty for now. See step 3.
2) Populate your LovelyCoconut/setup.py. This file contains information about the structure and status of your project.
from setuptools import setup
setup(
name='LovelyCoconut', #name of the project
version='1.0.0', #version
packages=["LovelyCoconut"] #name that you want to be able to import
)
3) Populate LovelyCoconut/LovelyCoconut/__init__.py. Copy the contents of your original `LovelyCoconut.py` module into it.
def bang_halves_together():
print("Clip clop clip clop")
4) Open a command prompt in the directory containing `setup.py` and execute `python -m pip install -e .`.
C:\Users\Kevin\CS101\homework\week2\originalContentDoNotSteal\LovelyCoconut>python -m pip install -e .
Processing C:\Users\Kevin\CS101\homework\week2\originalContentDoNotSteal\lovelycoconut
Installing collected packages: LovelyCoconut
Running setup.py install for LovelyCoconut ... done
Successfully installed LovelyCoconut-1.0.0
========================================================================
RESULT:
LovelyCoconut is now importable from any directory.
c:\>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import LovelyCoconut
>>> LovelyCoconut.bang_halves_together()
Clip clop clip clop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment