Ein Python-Paket veröffentlichen: drei Tools, zwei Befehle, keine Magie
Ein Skript aus einer einzigen Datei, das eine zufällige Tagesnachricht ausgibt, wird zu einem Befehl, den jeder weltweit mit pip installieren kann. Wer einen Schritt auslässt, zwingt Nutzer zu langsamen Source-Builds, und ohne Lizenz dürfen sie den Code überhaupt nicht verwenden. Backend Engineer Irina Truong von Parse.ly fragt, was wirklich zwischen einem funktionierenden Skript und einem Paket steht, das Fremde installieren können.
Verfolgen Sie den gesamten Weg von main.py zum per pip installierbaren Paket auf PyPI, mit Live-Demo
Irina Truong, Backend Engineer bei Parse.ly, zeigt, wie aus einem einzelnen Python-Skript eine per pip installierbare Konsolenanwendung auf PyPI wird. Sie behandelt Paketstruktur, setup.py-Metadaten und Entry Points, Source- und Wheel-Distributionen, das sichere Hochladen auf TestPyPI mit twine und API-Tokens sowie die Wahl einer Lizenz und betont, dass der gesamte Prozess keinerlei Magie enthält.
“Und im gesamten Prozess steckt keinerlei Magie.”
“Denn wenn Sie keine Lizenz beifügen, bedeutet das standardmäßig, dass andere keinerlei Erlaubnis haben, irgendetwas mit Ihrem Code zu tun. Sie dürfen ihn weder kopieren noch verbreiten noch verändern.”
What you will learn
Ein Python-Modul als Paket strukturieren: mit Paketverzeichnis, __init__.py, setup.py und README.
Metadaten, Classifiers und Konsolen-Entry-Points in setup.py so konfigurieren, dass Nutzer Ihr Tool als Shell-Befehl ausführen können.
Sowohl Source- als auch Wheel-Distributionen bauen und erklären, warum Wheels schneller installiert werden, besonders bei nativen Erweiterungen.
Sicher veröffentlichen: auf TestPyPI testen, mit einem in .pypirc gespeicherten API-Token und Upload per twine.
Eine Open-Source-Lizenz wie MIT oder GNU GPL v3 wählen und Changelog, Contributing Guide und Requirements-Dateien ergänzen.
Details
Level
Beginner
Format
Tech talk
Technical depth
Practitioner
For
Student, Early career, Mid-career
Length
40:25
Published
July 2020
Questions this talk answers
Was ist der Unterschied zwischen einer Python-Bibliothek und einer Python-Anwendung?
Bibliotheken sind installierbar, importierbar und versioniert und richten sich an Entwickler. Anwendungen haben dieselben Eigenschaften, sind aber zusätzlich ausführbar und richten sich an Endnutzer.
Warum sollte man sowohl eine Source-Distribution als auch ein Wheel bauen?
Eine Source-Distribution ist das ältere Format und muss auf dem System des Nutzers gebaut werden, während ein Wheel keinen Build-Schritt hat und schneller installiert wird. Am größten ist der Unterschied bei Paketen mit nativen Erweiterungen wie NumPy oder SciPy, und pip verwendet standardmäßig ein Wheel, wenn eines verfügbar ist.
Warum beim Hochladen ein API-Token statt Benutzername und Passwort verwenden?
Die Zugangsdaten liegen in einer Klartextdatei .pypirc in Ihrem Home-Verzeichnis, daher ist es sicherer, dort ein Token statt Login und Passwort zu speichern.
Was passiert, wenn ich ein Open-Source-Paket ohne Lizenz veröffentliche?
Ohne Lizenz haben andere standardmäßig keine Erlaubnis, Ihren Code zu kopieren, zu verbreiten oder zu verändern. Sie empfiehlt choosealicense.com, um eine passende Lizenz zu finden.
Wo stoßen Entwickler beim Veröffentlichen meist auf Hürden?
Typische Probleme sind, nur eine Source-Distribution und kein Wheel zu bauen, ein Paket genauso zu benennen wie ein bestehendes und vor einem erneuten Upload die Version nicht zu erhöhen.
Warum Wheels schneller installiert werden als Source-Builds (65 s)
API-Token statt Passwort verwenden (76 s)
Warum Veröffentlichen ohne Lizenz nach hinten losgeht (84 s)
Okay, so let's start. My name is Irina Truong. I work as a back-end engineer for a company called Parsley, and I'm going to be talking today about creating and publishing a Python package. So for this talk, there is actually no need to know Python. If you do, this is great. If you don't, you will still understand everything that's going on. If you want to follow along and create your own package, you do need a little knowledge of Python and a working interpreter. And to install a Python package, you would normally need a Python interpreter and pip, Python package installer. Most likely, if you are on a Mac or on a Linux, you already have that. If you are on Windows, you would have to install a Python distribution. And there are several of them for Windows. I know
specifically one from ActiveState. So here is the link to pip, pypa.io, to install pip if you don't have it yet. Python has two main types of packages. First of all, it's Python libraries. Python libraries have the following features. They are installable, importable and versioned. What does it mean? Well, you run a command to install a library and then you can import things from the library. So the library is going to expose functions for people to import. And of course, libraries are versioned. Libraries are written usually to target developers, not end users. They are useful for other other applications. And here we come to another type of Python package, which is application. So applications have all of the above features, installable, importable versions, but they also runnable. So you can run an application and it will probably give you some nice output like a web page or a console app. It may print out something for you. An application is built to target end users.
An application is built to target end users. And in this talk, I'm going to do a short demo with specifically a console application. So what's a console application? Um, if you worked as a developer in Linux, you would probably work in a terminal a lot. And a terminal window is this little black, boring window. Um, on my screen right An application is this little black right now. But it doesn't have to be quite so black right now. But it doesn't have to be quite so black and boring. There are console applications with quite a rich user interface. And you can see a couple of screenshots here.
So I made screenshots for midnight. And for H top, H top lets you see your machines activity, like processor load and stuff like this. So it doesn't have to be quite so black and boring. But normally, it's just a little window where you type in commands, and you see the output. And this is the output. And this is going to be my application. And this is going to be my application. You type in the command, and it tells you today's message. So it's going to tell you today is good for some kind of activity.
And right now I'm going to show the code for this application. So let's say this is my Python code, and it lives in the file called main dot py right now I don't have anything clear slate just one file. This is my main dot py. As you can see at the top of the package. At the top of the file, I import daytime and random package. Those are two packages from standard Python library.
And then I'm writing a function called today message. This function is going to return a string. And the string is going to say today is good for a certain activity. And the activity is going to be picked randomly. But the randomness is going to be specific for current daytime. Okay, so now I have this function, the function can be imported by other packages already. But I am going to develop a variable application here. And that's why I also need a main function, which actually going to call my today message and print the output.
And on the right of my screen here. This is how you run it right now. Python main dot py. So you call Python interpreter. And as an argument, you provide the script name. It tells me today is good for traveling. So can I share my code right now. It works, right? Why not? Well, kind of. To share your code right now, you would have to send main dot py module to people. And they would need a Python interpreter in their path. And they would run Python main dot py and see the wonderful today message.
Well, you think, how many people can I send my main file to? I don't know that many people. I want people from all over the world to be able to use it. So there must be a better way to share code. And for Python code, of course, there is. But before we can share it with the whole world, we need a few more things. First of all, a Python package has to be has to be in specific code structure, has to conform to a specific code structure.
Then you have to add a little bit of documentation and metadata, some directions for the installer tool. And then the upload to the packaging server. So your distribution needs to be uploaded to the centralized repository of Python packages. This is called py py. So our next step would be to create a package using our module. A Python file is just called a module.
Packages have a certain structure. And first you have to create a parent directory for the package. And then inside that you create a directory with the same name as your package. So in my case, it would be my advisor. Then I would put my main.py file inside my advisor directory. And next to it, I would create a special file called init.py.
You see that with double underscores around init. It's a special file that just tells Python interpreter this directory is a package. Next, I would have to create setup.py with instructions for the installer tool and a readme file. Readme can be several text based formats. Here I'm using a markdown file. So if you're going to share your code with people, if you're going to open source it, there's a few things that are nice to have.
First of all, you would probably want to have changelog, an author's file, a contributing guide, lists of requirements and a license. And we're going to talk a little bit more about those later. So first of all, let's take a quick look at setup.py. And setup.py, like I said, these are basically instructions for the installer tool, how to install your package on user system.
So it is also a Python file. And in the first line here, I import setup tools. Setup tools is also a Python package, but it's a package that knows how to install other packages. Then I call one function called setup from setup tools, providing a whole bunch of parameters. Let's go through the parameters. First of all, it has to be the name, the name of the package, of course.
And here it's my advisor. Then you have to provide a version, which is 001. Author name, my name, author email. That's my actual email here. Description gives useful advice. You saw it's very useful. A long description. For the long description, I'm using my readme file here. And I'm going to say that, okay, my long description is a markdown file.
So content type, search for that. And here is the second half of my setup.py. I have to provide a project URL. Usually they point to GitHub. But if you have like a complicated application, you may even create a dedicated website for your application. Next, I tell setup tools to go and find all packages in the current directory.
And then I provide an entry point. What's an entry point? Basically, I'm going to say, when this package is installed, I want an alias to be created to call my main function from the user shell. So instead of saying Python main.py, they're just going to say my advisor. They're just going to type the command called my advisor in the console.
Then I'm going to provide a list of classifiers. Here I specify that I developed this package in Python 3. I'm using an MIT license. And it's not dependent on any specific operating system. And optionally, you can provide that your package requires specific version of Python. For example, you are using some low language features and you need old Python like 2.7.
Or you're using some advanced language features and you want to use 3.6 and up. I actually think there is no reason for people to be using Python 2 anymore. Python 2 finally reached its end of life. So everybody wants to be using Python 3 now. And classifiers, usually you would want to include who the package is for.
So the audience of your package. Which license it's using. Which systems it can run on. The level of maturity. And possibly some other metadata. And you can go to pypi.org. Classifiers. And see a large searchable list of all possible Python classifiers. Okay, so what are entry points? In Python, entry points are very useful packaging features. They allow you to export functions.
Or to extend your package with plugins. Right now we exported one function here. This is a function called main. Inside the package MyAdvisor. And I created an alias or a shortcut for it called MyAdvisor. You can also extend your package with plugins. So your package could provide entry points for other packages to plug into. And add some functionality to your package.
This one is a very fun one. But we're not going to be talking about it here. So here is my minimal readme file. You don't need that much information about my package. Because it's very simple. It just has a title. And one paragraph about what it does. But perhaps if you had a more complicated package than mine is.
You could describe all the different parameters. And options. And use cases. How to call it. How to use it. You could include all kind of information in the readme. So the next thing to do is packaging it up. And here, first I'm going to install a couple more Python tools. So I'm going to use pip installer. And call pip install setup tools and wheel.
Are two packages that are going to be used to create a distribution. Next, once I did that. I'm going to call Python setup.py sdist and bdist will. What does it all mean? sdist, this option is going to create a source distribution out of my package. Source distribution. It's basically going to wrap my source code in a type of archive.
And on a user system, it will have to be built and put in the right place. Bdist will. It's going to create a will distribution, which is a built distribution. This universal flag says that my will is good for any Python and any system architecture. So what just happened after I ran those commands, I'm going to have a dist subdirectory in my parent directory.
And there's going to be two files there. As I just said, this command above, it created two types of Python distributions. First, we have a source distribution. This is the tar file. And second, this is build distribution. And that's a wheel file. So WHL files are called wheels. Let's look inside. So tar file is an archive. And we can list the contents of the archive and see what's inside.
So here on this slide, all the files in black. Those are my files. You just saw that I created them and added them inside my package. And those files in blue, I did not have those before. Setup tools went and created those files and put some metadata in it. If you actually build your archive and take a look inside, usually those extra files, they are just text files.
You can see the contents if you're curious, but you don't actually need to know what goes inside. Setup tools deals with all of that. And wheel file is a build distribution. But the WHL extension is just hiding that it's really a zip archive. So we can look inside a zip archive and see that it has all the same init.py and main.py.
Those are mine. And a bunch of files, again, where it put some metadata and it created a wheel file. So all the metadata is pretty much, if you look at it, it's going to be taken from my setup.py, where I put in all the extra information about my package. So why do we need two types of distributions?
A source distribution is an older Python packaging format. A wheel distribution is a newer one and it's quicker to install. So even for pure Python packages, it is quicker to install because there is no build step. The package is just going to be pretty much put in the right place on the user system. But especially it's much faster for packages with native extensions.
If you ever used any Python packages for data science, such as numpy or scipy, they have lots of built C extensions. If you have to build them on your system, it takes a really long time. If you're using a wheel to install the package, and by default, pip actually will use a wheel if it's available for your system architecture, it goes much, much faster.
So let's take a look at the name of our wheel distribution. First of all, it's going to include a package name. Then it's going to include a package version, Python tag. In my case, it's tagged for Python 2 and Python 3 because I used the universal flag. Then application binary interface. Here I'm not targeting any specific binary interface, so it says none.
And then a platform tag. And again, it says any because I'm not targeting any specific operating system. So next thing to do would be to upload it to PyPI server. I'm going to create an account. And first of all, you want to create an account on the test server, not the actual Python packaging server. So you would go to test.pypi.org and register an account.
And as usual, you would provide your email address. It would send you a link to verify your email. Once you have that, you can already upload your package to PyPI. But I'm going to create a new API token here because it's always better to use a token and not a login password on your system because you have to store it in the text file.
So it's better to store a token in a file than your login and password because, you know, people can take a look at your login and password in a plain text file. That's not a good thing. So we're going to go and configure the test server in special file called PyPI RC. The special file lives in your home directory.
This is how PyPI RC file looks. So first you create an entry for test PyPI server and you're going to say username is a token because you're going to use a token and not login and password. And then in place of a password, you provide the actual token that you received on PyPI website. I didn't put an actual token here.
So next step, we would upload our package to PyPI server. For that, we need yet another Python tool. And that Python tool is called twine. I'm going to run pip install twine. That will install the twine package. And then I'm going to call twine upload all files from my disk sub directory. And I'm going to say the repository is test PyPI, which is the one I just configured.
So it's the same name as in my PyPI RC file. Okay, so once I did that, hopefully it uploaded successfully. I'm going to pip install it, my package, just to test it and make sure it works. I'm going to pip install my advisor providing the index URL to test pypi.org. You only need this index URL if you're installing from the test server.
Otherwise, it knows the URL of the actual Python packaging server. You would normally just say pip install package name. So pip install my advisor. And then once I installed it, I can run it in terminal and see the today's message. And as you can see, I run my advisor. So it created the shell command for me. I don't need to run Python main.py anymore.
Let's talk a little bit about the license. A lot of people use MIT or GNU GPL v3 license for their open source packages. And this is the two on my slide here. MIT license is very popular. It pretty much allows everybody to do anything they want with their source code. So people can copy, distribute or modify their source code, your source code.
You basically submit all the rights. You don't want to keep any copyright. With GNU GPL v3, that is another very commonly used. People cannot close the source. So sometimes you distribute your code. And with MIT license, people can actually compile your code and distribute it pre-compiled. So nobody else can change the source. With GNU GPL v3, this is not allowed.
Anytime you distribute the source, you'll have to provide the actual source and not just the build distribution. Because people may want to modify it. And you might say, okay, I don't care what people do with my code. I don't want to worry about the license. I'm going to provide no license. That's actually not a good option for open source package.
Because when you include no license, by default, it means people don't have any permissions to do anything with your code. They can't copy, distribute or modify it. If you are developing your package inside the community, let's say your package is part of Apache community, for example. The community may already have a preferred license and you don't have to worry about picking one.
But if you do want to pick a license for your own package, you can go to choosealicense.com. And it has a very nice interactive wizard type of web page where you can specify your requirements and pick a type of license that fits your package best. And you can also see a huge comparison table of all the license options available.
Let's talk a bit more about optional but useful things. So, change log. What is change log? It's useful for the users of your application but also for developers. You would track all the changes, all the bug fixes and new features by date and version. And you can understand how it's useful, right? So, some user is having a problem with your application.
Something is not working correctly. They can take a look at the change log and see, do I have the latest version? Perhaps my issue is already fixed in the latest version. And they can see, like, which version they need to install. Perhaps they currently have a 1.0 and the bug is fixed in version 2.0, right? So, they just need to install 2.0.
For contributors, you might want to keep a list of authors in the authors file for copyright purposes or simply to give people credit. And for developers, you might want to have a contributing guide. So, it's pretty much a text file where you would describe to people that want to work on your application how best to do that.
So, first of all, you would probably want to put environment setup into that file. If you have a specific code style. If you have a git workflow you want to conform to. How you go into your review PRs. What are the requirements for aiding tests. What frameworks you use for testing. And stuff like that. So, this file is useful for developers.
Next, if you have any Python dependencies, which are not part of the standard library, you would provide a requirements.txt. So, requirements.txt usually serves as a list of requirements that your application needs. So, your dependencies. And requirements.dev.txt. This is a file that you would put in your package if you want to give your developers a list of what you are using to test, build, or publish your package.
An easy way to create a list of requirements with Python is a pip freeze command. And an easy way to install requirements from the requirement.txt file is pip install -r. Okay, so, now you pretty much know everything about creating and building a Python package. So, let's summarize. What did it take? We wrote some code here. We added the setup file with some metadata.
We added a license and documentation. The readme file. We had to install three tools. Setup tools, will, and twine. And we ran just two commands. Python setup.py and twine upload. And there is no magic whatsoever in the whole process. And I have a short demo. So, I'm going to share my other screen here. Okay, so, here is a demo of me working on my package and uploading the package to PyPI server.
So, I just created and activated a virtual environment, which is just part of a development workflow. Now, I'm going to install my setup tools, wheel and twine. So, it's going to run for a bit. It goes pretty quickly. And I'm going to update the version in my setup.py file. Because you cannot re-upload the package to the test server with the same version.
Same name and same version. So, I'm going to work. And I already uploaded it before. Okay. So, you can see I have two distribution files here. And next, I'm going to call this twine upload command. It's going and it's done very quickly. So, I just deactivated my environment because I want to install my package from test server in a clean environment.
And there it goes. Okay. And that's it. That's the whole demo. It runs in about one minute. Let me share my other presentation. The code that you saw in this demo, I shared it on GitHub. Here's the link. I'm going to stay on this slide for a little bit so you guys can copy if you like. So, my GitHub login is j.bennett and the package name or the repo name is myadvisor.
And here are some useful links. First link is the link to my slides. This is a short link. Second link is the link to my demo that I just showed you. And then some documentation links to Python packaging guide. The documentation about Python package installer and Python wheels. Those are optional if you want more information about Python packaging.
You don't actually need to know anything, any of that, to build and publish your own package. As you saw, a few commands. That's all it takes. Here is my contact information. If you want to contact me, find me on Twitter or send me an email. Okay, I'm going to switch back to the link slide. But that's it.
Right now we have time for questions. Let me take a look. Do you see, did you have any questions that I didn't answer yet? Rest in peace Python 2. Yes. Python is pure magic. Oh, was the font too small to read? Well, there is a link to my demo. So you can actually take a look for yourself and increase it.
Full screen is for yourself. I think it's better. Oh, it needs access. Okay, I'm going to check after this demo, make sure that it's in common access. So the link to this slide is is dot GD A R A V O J. Anybody was able to open that? The link works? Okay. Okay, good. Do I have Kaggle?
Nope, I don't have Kaggle. So it's like package JSON and JavaScript. What is like package JSON and JavaScript? Okay. Do you set up that PY? I think so. Well, which part of this process are developers likely to experience friction or obstacles during? Huh, that's a good question. Well, first of all, people may not know to build a wheel or why they need to build a wheel and just build an S-dist.
And that makes it less efficient for other people to install their application. Second, you might experience problems if you named your package the same as some other package. Or if you're trying to upload the same version, if you forgot to update the version. No, the slides should not require requesting access. Huh. So it works for some people, but not for other people.
Okay. Got that. I'm going to make it public after this demo. Eh. This is silly. Let me see. Okay. Can you try the short link again, guys? And can you also try this link in the chat right now? Lonely works. Does the short link work as well or not? Perfect. Okay, great. Do you guys have any more questions?
Okay, if there is no more questions, then I'm going to go and give you the rest of the time, which is like three minutes. You can have them back. Oh, if I'm new and learning. Yes, absolutely. You can upload a package to the test server first. It works the same way as the regular package in Python server.
And after a few weeks, I think the packages are actually deleted from test server. So if you worried about somebody and some people installing them by mistake, you know, and they are broken or something, don't worry. They're going to be just cleared from the test server and they're not going to be there in a short time. And the test puppy and the test PI PI server and the real PI PI server, they require two different logins, but they work absolutely the same in terms of the workflow.
The summary slide, let's switch to the summary slide. Okay, some code, some metadata, some documentation and license install three tools, set up tools will entwine and run two commands. Is there any cost when you register the test PI PI? No, it's free. And the regular PI PI is free as well. And it's usually a good idea before you create a package to search if a package similar to what you want to do already exists.
So you can search by name, by description. You go to PI PI dot org, I think it's org, and just do a search. How can we be as cool as you? Thank you for the compliment. Can we use test PI PI with data science projects? If your project is a Python package, you can absolutely upload it to PI PI.
Okay. What is the first package you ever made? Hmm. My first ever open source application is called Warfi. It's still on GitHub. And in PI PI, you can install it. It's a CLI for Docker. So I think, do I still have a website? Yes. Okay. I have an actual website for my first package. What my best regular expression was.
Oh, my goodness. It's really hard to remember just one, you know? I wrote a lot of regular expressions in my career. Sorry. Can't answer that one. Okay. I think we only have a few seconds left. Wait. Selected the name? What? For how many years have you worked with Python? For the last six years. Python is a very easy language to learn.
I actually learned it by myself. Okay. I think I have to say goodbye because the session is going to end. Bye, everyone.
Transcribed automatically; names checked against the speaker record. Select a time to jump there.
Article based on this talk
Was es wirklich braucht, ein Python-Paket auf PyPI zu veröffentlichen
Irina Truong zeigt, wie aus einem einzelnen Skript mit etwas Struktur, einigen Metadaten und drei Standard-Tools ein per pip installierbarer Befehl wird.
Kurz gesagt
Ein Python-Paket zu veröffentlichen ist vor allem eine Frage von Struktur und Metadaten, nicht von Magie. Irina Truong, Backend Engineer bei Parse.ly, nimmt ein Konsolenskript aus einer einzigen Datei, gibt ihm ein Paketlayout und eine setup.py, baut Source- und Wheel-Distributionen, lädt sie mit twine auf den Test-Server von PyPI hoch und installiert das Ergebnis als Shell-Befehl. Dabei erklärt sie, warum Wheels wichtig sind, warum API-Tokens besser sind als Passwörter und warum eine Veröffentlichung ohne Lizenz ein Fehler ist.
Die wichtigsten Erkenntnisse
Ein Python-Modul als Paket strukturieren: mit Paketverzeichnis, __init__.py, setup.py und README.
Metadaten, Classifiers und Konsolen-Entry-Points in setup.py so konfigurieren, dass Nutzer Ihr Tool als Shell-Befehl ausführen können.
Sowohl Source- als auch Wheel-Distributionen bauen und erklären, warum Wheels schneller installiert werden, besonders bei nativen Erweiterungen.
Sicher veröffentlichen: auf TestPyPI testen, mit einem in .pypirc gespeicherten API-Token und Upload per twine.
Eine Open-Source-Lizenz wie MIT oder GNU GPL v3 wählen und Changelog, Contributing Guide und Requirements-Dateien ergänzen.
Vom Skript zu etwas, das sich zu teilen lohnt
Truong unterscheidet zu Beginn die zwei wichtigsten Arten von Python-Paketen. Bibliotheken sind installierbar, importierbar und versioniert und stellen Funktionen bereit, die anderer Code nutzt. „Bibliotheken werden meist für Entwickler geschrieben, nicht für Endnutzer.“ (1:04) Anwendungen teilen diese Eigenschaften, sind aber zusätzlich ausführbar und erzeugen eine Ausgabe, etwa eine Webseite oder eine Konsolenanwendung.
Ihr durchgehendes Beispiel ist eine kleine Konsolenanwendung: eine Datei main.py, die mit zwei Modulen der Standardbibliothek eine Nachricht ausgibt, wofür der heutige Tag gut ist, wobei die Aktivität für das aktuelle Datum zufällig gewählt wird. Das funktioniert, doch zum Teilen müsste man die Datei per E-Mail an Leute schicken, die bereits einen Python-Interpreter haben. Ihre Reaktion fasst die Motivation der ganzen Session zusammen: „Ich möchte, dass Menschen auf der ganzen Welt es nutzen können. Es muss also einen besseren Weg geben, Code zu teilen.“ (5:36)
Paketstruktur und setup.py für den Code
Der erste Schritt ist das Layout. Truong legt ein übergeordnetes Verzeichnis an, erstellt darin ein Verzeichnis mit dem Namen des Pakets, verschiebt main.py dorthin und fügt eine Datei __init__.py hinzu. „Das ist eine spezielle Datei, die dem Python-Interpreter einfach mitteilt, dass dieses Verzeichnis ein Paket ist.“ (7:11) Neben das Paket legt sie setup.py und ein README in Markdown und empfiehlt für alles, was als Open Source veröffentlicht wird, einen Changelog, eine Autorendatei, einen Contributing Guide, Requirements und eine Lizenz.
Die Datei setup.py ist selbst Python. Sie importiert setuptools und ruft eine einzige setup-Funktion mit Paketname, Version, Angaben zur Autorin, einer Kurzbeschreibung und einer ausführlichen Beschreibung aus dem README auf. Außerdem nennt sie eine Projekt-URL (meist GitHub), findet die Pakete im Verzeichnis und deklariert Classifiers für Python-Version, Lizenz, Betriebssystem, Zielgruppe und Reifegrad, die sich auf pypi.org durchsuchen lassen. Der nützlichste Parameter für ein Konsolentool ist der Entry Point, der einen Shell-Alias für die main-Funktion erzeugt. „Statt Python main.py sagen sie also einfach my advisor.“ (9:53)
Warum sowohl Source-Distribution als auch Wheel
Sind setuptools und wheel installiert, erzeugt ein einziger Befehl zwei Dateien in einem Unterverzeichnis dist: ein tar-Archiv mit der Source-Distribution und eine .whl-Datei, die eigentlich ein zip-Archiv ist. Truong öffnet beide und zeigt ihre eigenen Dateien neben den aus setup.py generierten Metadaten-Dateien. Sie erklärt, warum es beide Formate gibt: „Eine Source-Distribution ist ein älteres Python-Paketformat. Eine Wheel-Distribution ist ein neueres und lässt sich schneller installieren.“ (16:19)
Wheels haben keinen Build-Schritt, sodass selbst reine Python-Pakete schneller installiert werden, und bei Paketen mit nativen C-Erweiterungen wie NumPy und SciPy ist der Gewinn groß. Sie weist darauf hin, dass pip standardmäßig ein Wheel verwendet, wenn eines für das System des Nutzers verfügbar ist. Außerdem entschlüsselt sie den Wheel-Dateinamen: Paketname, Version, Python-Tag, ABI-Tag (Application Binary Interface) und Plattform-Tag, die in ihrem universellen Build für beliebige Plattform und keine bestimmte Binärschnittstelle stehen.
Sicher hochladen mit TestPyPI und twine
Truong rät, sich zuerst auf test.pypi.org statt auf dem echten Index zu registrieren und ein API-Token zu erstellen, statt sich auf Login und Passwort zu verlassen, denn die Zugangsdaten liegen in einer Klartextdatei .pypirc im Home-Verzeichnis. „Es ist also besser, ein Token in einer Datei zu speichern als Ihren Login und Ihr Passwort, weil, Sie wissen schon, Leute Ihren Login und Ihr Passwort in einer Klartextdatei einsehen können.“ (18:54)
Nach der Installation von twine lädt sie alles aus dem Verzeichnis dist in das konfigurierte Test-Repository hoch, installiert das Paket dann mit pip über die URL des Test-Index und führt es als einfachen Shell-Befehl aus. In der Fragerunde ergänzt sie, dass beide Server kostenlos sind, dass Pakete auf dem Test-Server nach einigen Wochen gelöscht werden und dass die häufigsten Hürden ein fehlendes Wheel, ein bereits vergebener Name und eine vor dem erneuten Upload nicht erhöhte Version sind.
Lizenzen und Dateien, die anderen helfen
Beim Thema Lizenzen stellt Truong die permissive MIT-Lizenz der GNU GPL v3 gegenüber, die verlangt, dass der Quellcode bei jeder Weitergabe des Codes verfügbar bleibt. Sie warnt davor, die Lizenz wegzulassen: „Denn wenn Sie keine Lizenz beifügen, bedeutet das standardmäßig, dass andere keinerlei Erlaubnis haben, irgendetwas mit Ihrem Code zu tun. Sie dürfen ihn weder kopieren noch verbreiten noch verändern.“ (22:44) Als Entscheidungshilfe verweist sie auf den interaktiven Assistenten und die Vergleichstabelle auf choosealicense.com und merkt an, dass Communities wie Apache womöglich bereits eine bevorzugte Lizenz haben.
Anschließend behandelt sie die optionalen Dateien: einen Changelog, damit Nutzer prüfen können, ob ihr Bug in einer neueren Version behoben ist, eine Autorendatei zur Würdigung, einen Contributing Guide zu Einrichtung der Umgebung, Codestil, Git-Workflow und Tests sowie mit pip freeze erzeugte Requirements-Dateien. Ihr Fazit ist beruhigend: etwas Code, Metadaten, Dokumentation und eine Lizenz, drei Tools und zwei Befehle. „Und im gesamten Prozess steckt keinerlei Magie.“ (26:56)
Den Vortrag ansehen
How to create and publish a Python package, Irina Truong, etwa 40 Minuten: https://www.womentech.net/video/irina-truong-how-create-and-publish-python-package
Über die Speakerin
Irina Truong ist Backend Engineer bei Parse.ly. Sie lebt mit ihrem Mann, zwei Kindern und einer Katze im sonnigen Kalifornien.
Fragen, die dieser Vortrag beantwortet
Was ist der Unterschied zwischen einer Python-Bibliothek und einer Python-Anwendung?
Warum sollte man sowohl eine Source-Distribution als auch ein Wheel bauen?
Warum beim Hochladen ein API-Token statt Benutzername und Passwort verwenden?
Was passiert, wenn ich ein Open-Source-Paket ohne Lizenz veröffentliche?
Wo stoßen Entwickler beim Veröffentlichen meist auf Hürden?
Mit KI aus dem Vortragstranskript erstellt. Redaktionelle Prüfung ausstehend.
Resources mentioned
pip installation guide (pip.pypa.io)
test.pypi.org
pypi.org classifiers list
choosealicense.com
Python Packaging User Guide
pip documentation
Python wheel documentation
Speaker's myadvisor demo repository on GitHub
Cite this talk
Irina Truong. "How to create and publish a Python package." WomenTech Network, 2020. https://www.womentech.net/video/irina-truong-how-create-and-publish-python-package