Than the specified length, it will be returned unchanged. Returns a string, which will be padded on the left with characters if necessary. They allow you to write examples in the docstrings of your code, and then doctest will execute the examples and verify that the actual code matches your documentation: def left_pad(input, length, fill_character=' '): Let’s make sure that our code correctly executes these examples.Ī great way to unit test Python is by using doctests. If you go to the npm (Node package manager, pip for JavaScript) page for left-pad, there are several examples listed there. Return str(input).rjust(length, str(fill_character)) Unlike JavaScript, the Python standard library has a method for this, and our ‘business logic’ is a single line of code: def left_pad(input, length, fill_character=' '): The function we need to write is simple: we get a string or a number, and if it is smaller than the specified length, we should add fill characters on the left side until we reach that length. Let’s start by creating a new Pure Python project, and writing the application. We’ll create the setup.py file later using P圜harm. In this case, we’ll pick a permissive open source license, I’ll use the Apache 2.0 license, but for your own project, you can use the MIT license or something else. People can’t use your code without a license. If you’d prefer to use Markdown or another file format, you need to add a setup.cfg file where you specify the name of the file.įurthermore, you need to pick a license for your code.
You can read more about ReStructuredText in the Sphinx documentation. We’ll need to write a README file, the default for Python is to use ReStructuredText for these. To make our package work with PyPI (which really means, to make it work with distutils), our package needs to have several files: - Root directory (name doesn't matter) To do so, just use the search box on the top right of the PyPI page. It is important to check if the intended name of your package is free on PyPI before you start. However, his package has neither unit tests nor a GitHub repository so we can do better! We’ll make a drop-in replacement which we’ll name ‘pad-on-left’. Someone has already been helpful and released a left-pad package on PyPI. A great example of this dedication to reuse is the excellent ‘left-pad’ library, and today we will write a clone of this library to bring this greatness to the Python community! JavaScript developers are great at sharing code: if someone writes functionality, they share it so that others don’t have to reinvent the wheel (it doesn’t stop them from doing so however). Let’s create a simple package and go through the process of publishing it! Today’s Package: Left Pad The pythonic way of sharing a package is making it available on PyPI.
When you’ve written some great code, you might want to make this available for others to use as well.