Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Creating Packages

00:00 Let’s create a package structure. I’m here in my terminal, but you can totally create those files in your Windows Explorer or your mac Finder or on your Linux file application app, which name I don’t know, but you can also follow me along with the terminal.

00:20 Navigate to the desktop and create a folder named packages_example/. Then navigate into this folder.

00:34 And in this folder, create another folder. And this one, you name mypackage/.

00:43 The packages_example folder is called the project folder, or project root folder, because it will contain all the files and folders in the packages_example/ project.

00:55 The mypackage/ folder will eventually become a Python package. It isn’t one right now because it doesn’t contain any modules. So to change that, hop over to IDLE and create a new editor window.

01:10 As mentioned before, to make a folder a Python package, you need to have a __init__ file in it. So never forget to have __init__ in it. Yeah, and as mentioned before, also this file can be empty.

01:24 So without adding any content to it, save a new file from your IDLE editorial window as __init__.py in the mypackage/ subfolder of your packages_example/ folder

01:44 Then open another window and add the following function: def greet(name): And then on the next line, indented, print(). And then let’s do an f-string: f"Hello, {name}!" and the closing parentheses.

02:12 So there is a greet() function that takes name, and inside greet(), you call the print() function, and then you print a string, Hello, with the name that was passed into the function.

02:25 Save this file as module1.py in the same folder as the __init__ file. And to make the package complete, create a new file in your IDLE editor with this code—def depart():—which takes one parameter, which is name. And inside the function body, again a print() function call.

02:49 And this time, you use an f-string saying goodbye, and then in curly braces the name.

02:59 Just like before, you’ll save this file in the mypackage/ subfolder. And you name this file module2.py,

03:11 and that’s a package. With this structure, the files, and the code in place, you are now ready to import and use these modules in another module.

Natasha Kaplan on Dec. 27, 2023

Where is the PC version for this?

Martin Breuss RP Team on Jan. 3, 2024

@Natasha Kaplan all the commands that Philipp uses should work the same on a Windows system, if you’re using PowerShell.

You can check out the additional context and instructions on using the terminal in these resources:

Hope this helps!

Become a Member to join the conversation.