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
- Create
helpers.pywith your functions. - Save it next to your notebook or script.
- Write
import helpersorfrom helpers import clean_city. - 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.
Ravindra Bagale's Tip – मराठी
Jupyter मध्ये helpers.py बदलल्यावर kernel restart करा (किंवा %load_ext autoreload आणि %autoreload 2 वापरा) म्हणजे नवा code load होतो.
Ravindra Bagale's Tip – हिंदी
Jupyter में helpers.py बदलने के बाद kernel restart करो (या %load_ext autoreload और %autoreload 2 इस्तेमाल करो) ताकि नया code load हो.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.