Creating Python packages

Creating Python packages

Introduction

Every package requires a setup.py file which describes the package.

Consider the following directory structure for a simple package:

+-- package_name
| |
+-- init.py
+-- setup.py

The init.py contains only the line def foo(): return 100.

The following setup.py will define the package:

from setuptools import setup
setup(
name='package_name', # package name
version='0.1', # version
description='Package Description', # short description
url='https://example.com', # package URL
install_requires=[], # list of packages this package depends
# on.
packages=['package_name'], # List of module names that installing
# this package will provide.
)

virtualenv is great to test package installs without modifying your other Python environments:

virtualenv .virtualenv

source .virtualenv/bin/activate
python setup.py install running install

Installed …/package_name-0.1-….egg

python

import package_name
package_name.foo() 100

Uploading to PyPI

Once your setup.py is fully functional (see Introduction), it is very easy to upload your package to PyPI.

Setup a .pypirc File

This file stores logins and passwords to authenticate your accounts. It is typically stored in your home directory.

.pypirc file

GoalKicker.com – Python® Notes for Professionals 390

[distutils]
index-servers =
pypi
pypitest
[pypi]
repository=https://pypi.python.org/pypi
username=your_username
password=your_password
[pypitest]
repository=https://testpypi.python.org/pypi
username=your_username
password=your_password

It is safer to use twine for uploading packages, so make sure that is installed.

$ pip install twine

Register and Upload to testpypi (optional)

Note: PyPI does not allow overwriting uploaded packages, so it is prudent to first test your deployment on a dedicated test server, e.g. testpypi. This option will be discussed. Consider a versioning scheme for your package prior to uploading such as calendar versioning or semantic versioning.

Either log in, or create a new account at testpypi. Registration is only required the first time, although registering more than once is not harmful.

$ python setup.py register -r pypitest

While in the root directory of your package:

$ twine upload dist/* -r pypitest

Your package should now be accessible through your account.

Testing

Make a test virtual environment. Try to pip install your package from either testpypi or PyPI.

Using virtualenv $ mkdir testenv
$ cd testenv
$ virtualenv .virtualenv

$ source .virtualenv/bin/activate
Test from testpypi
(.virtualenv) pip install --verbose --extra-index-url https://testpypi.python.org/pypi
package_name

Or test from PyPI

(.virtualenv) $ pip install package_name

(.virtualenv) $ python
Python 3.5.1 (default, Jan 27 2016, 19:16:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import package_name

GoalKicker.com – Python® Notes for Professionals 391

package_name.foo()
100

If successful, your package is least importable. You might consider testing your API as well before your final upload to PyPI. If you package failed during testing, do not worry. You can still fix it, re-upload to testpypi and test again.

Register and Upload to PyPI

Make sure twine is installed:

$ pip install twine

Either log in, or create a new account at PyPI.

python setup.py register -r pypi
twine upload dist/*

That’s it! Your package is now live.

If you discover a bug, simply upload a new version of your package.

Documentation

Don’t forget to include at least some kind of documentation for your package. PyPi takes as the default formatting language reStructuredText.

Readme

If your package doesn’t have a big documentation, include what can help other users in README.rst file. When the file is ready, another one is needed to tell PyPi to show it.

Create setup.cfg file and put these two lines in it:

[metadata]
description-file = README.rst

Note that if you try to put Markdown file into your package, PyPi will read it as a pure text file without any formatting.

Licensing

It’s often more than welcome to put a LICENSE.txt file in your package with one of the OpenSource licenses to tell users if they can use your package for example in commercial projects or if your code is usable with their license.

In more readable way some licenses are explained at TL;DR.

Making package executable

If your package isn’t only a library, but has a piece of code that can be used either as a showcase or a standalone application when your package is installed, put that piece of code into main.py file.

Put the main.py in the package_name folder. This way you will be able to run it directly from console:

python -m package_name

GoalKicker.com – Python® Notes for Professionals 392

If there’s no main.py file available, the package won’t run with this command and this error will be printed:

python: No module named package_name.main; ‘package_name’ is a package and cannot be directly executed.

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment