Python - Modules

Hello there, future Python wizards! Today, we're going to embark on an exciting journey into the world of Python modules. Don't worry if you're new to programming; I'll be your friendly guide, explaining everything step by step. So, grab your virtual wand (keyboard), and let's dive in!

Python - Modules

Python Modules

Imagine you're building a magical castle (your program). Instead of constructing everything from scratch, wouldn't it be great if you had pre-built towers, walls, and gates that you could just snap into place? That's exactly what modules are in Python - pre-written code that you can easily use in your programs.

Python Built-in Modules

Python comes with a treasure chest of built-in modules. These are like free magical spells that you can use right away. Let's try one!

import random

# Generate a random number between 1 and 10
magic_number = random.randint(1, 10)
print(f"Your magic number is: {magic_number}")

In this example, we're using the random module to generate a random number. It's like pulling a rabbit out of a hat, but with numbers!

Python User-defined Modules

While built-in modules are great, sometimes you need to create your own magical spells. That's where user-defined modules come in handy.

Creating a Python Module

Let's create a simple module called magic_spells.py:

# magic_spells.py

def levitate(object):
    return f"{object} is floating in the air!"

def disappear(object):
    return f"{object} has vanished into thin air!"

Now we have our own module with two magical functions!

The import Statement

To use our newly created module, we need to import it:

import magic_spells

# Use the functions from our module
print(magic_spells.levitate("book"))
print(magic_spells.disappear("rabbit"))

Output:

book is floating in the air!
rabbit has vanished into thin air!

The from ... import Statement

Sometimes, you only need specific spells from a module. That's where from ... import comes in handy:

from magic_spells import levitate

# Now we can use levitate directly without magic_spells prefix
print(levitate("chair"))

Output:

chair is floating in the air!

The from...import * Statement

If you want to import all spells from a module, you can use from...import *:

from magic_spells import *

# Now we can use all functions directly
print(levitate("table"))
print(disappear("hat"))

However, be careful with this one! It's like opening Pandora's box - you might accidentally overwrite existing functions if they have the same name.

The import ... as Statement

Sometimes, module names can be long or confusing. You can give them a nickname using import ... as:

import magic_spells as spells

print(spells.levitate("pencil"))

Locating Modules

Python looks for modules in several places:

  1. The current directory
  2. PYTHONPATH (if set)
  3. The installation-dependent default directory

The PYTHONPATH Variable

PYTHONPATH is like a magical map that tells Python where to find additional modules. You can set it in your system's environment variables.

Namespaces and Scoping

Think of namespaces as different realms in your magical world. Each module has its own namespace, preventing conflicts between similarly named functions or variables.

Module Attributes

Modules have special attributes. Let's explore some:

import magic_spells

print(magic_spells.__name__)  # Prints the name of the module
print(magic_spells.__file__)  # Prints the file path of the module

The name Attribute

The __name__ attribute is special. It's __main__ when the script is run directly, and the module's name when imported.

# In magic_spells.py, add:
if __name__ == "__main__":
    print("This module is being run directly")
else:
    print("This module is being imported")

The dir() Function

The dir() function is like a magical mirror that shows you all names defined in a module:

import magic_spells

print(dir(magic_spells))

The reload() Function

If you make changes to a module and want to reload it without restarting Python, you can use reload():

from importlib import reload
import magic_spells

# Make changes to magic_spells.py
reload(magic_spells)

Packages in Python

Packages are like spell books that contain multiple modules. They're simply directories with a special __init__.py file.

Here's a table summarizing the import methods we've learned:

Method Syntax Example
Basic Import import module_name import magic_spells
From Import from module_name import function_name from magic_spells import levitate
Import All from module_name import * from magic_spells import *
Import as Alias import module_name as alias import magic_spells as spells

And there you have it, apprentices! You've just learned the basics of Python modules. Remember, practice makes perfect, so keep experimenting with different modules and create your own magical Python world. Happy coding!

Credits: Image by storyset