Ravindra BagaleCourses & study guides मराठी Track your progress

Python Modules, pip and Virtual Environments (venv) Explained for Beginners

P10.6 How to Create Your Own Python Module

Why. When the same helper functions appear in many notebooks, move them into one .py file and import it everywhere.

What. Any .py file in the same folder can be imported by its file name (without .py).

How.

Make a module

  1. Create helpers.py with your functions.
  2. Save it next to your notebook or script.
  3. Write import helpers or from helpers import clean_city.
  4. Call the function.

Worked example A — Import your own helper.

Step 1 — What we do. A data team keeps money and cleaning helpers in helpers.py.

Step 2 — Make the input file helpers.py in the same folder as your code:

def clean_city(s):
    return s.strip().title()

def money(x, symbol="₹"):
    return f"{symbol}{x:,.2f}"

About this data: this file is code, not data: two small helper functions.

Step 3 — Type and run this code.

from helpers import clean_city, money
print(clean_city("  pUNE "))
print(money(1234.5, "£"))

Step 4 — Output you should see.

Pune
£1,234.50

Step 5 — What it means. Your functions now work like any library. Fix a bug once in helpers.py and every notebook gets the fix.

Ravindra Bagale's Tip

In Jupyter, after you edit helpers.py, restart the kernel (or use %load_ext autoreload and %autoreload 2) so the new code is loaded.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.