> Source URL: /resources/modules.guide
# Modules

A module is a Python file containing code you can import and reuse.

## Importing Modules

```python
import random

number = random.randint(1, 10)
print(number)
```

## Import Specific Items

```python
from random import randint, choice

number = randint(1, 10)
color = choice(["red", "blue", "green"])
```

## Import with an Alias

```python
import random as r

number = r.randint(1, 10)
```

## Useful Standard Library Modules

These come built into Python:

### random

```python
import random

random.randint(1, 100)              # Random integer from 1 to 100
random.choice(["a", "b", "c"])      # Random item from list
random.shuffle(my_list)             # Shuffle list in place
```

### csv

```python
import csv

with open("data.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)
```

### json

```python
import json

# String to dictionary
data = json.loads('{"name": "Alice"}')

# Dictionary to string
text = json.dumps({"name": "Alice"})
```

### os

```python
import os

os.path.exists("file.txt")    # Check if file exists
os.listdir(".")               # List files in directory
```

### datetime

```python
from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d"))
```

## Installing External Packages

Beyond the standard library, you can install packages from **PyPI** (the Python Package Index) using a package manager. In this course we use `uv`. See the [Packages and uv Guide](./packages.guide.md) for setup and usage.

## Creating Your Own Modules

Any Python file can be imported as a module:

```python
# helpers.py
def greet(name):
    return "Hello, " + name + "!"
```

```python
# main.py
from helpers import greet

print(greet("Alice"))
```

Output:

```
Hello, Alice!
```

When your project has multiple files, use the `__name__` guard and a `main()` function to keep things organized. See the [Project Structure Guide](./project-structure.guide.md) for the full pattern.

## Common Mistakes

**Naming your file the same as a module**

```python
# If your file is named random.py:
import random  # Imports YOUR file, not the built-in module!

# Solution: rename your file to something else
```

**Forgetting to install a package**

```python
import requests  # Error if not installed!

# Fix: uv add requests
```

**Importing from the wrong location**

```python
# Wrong - helpers.py is in a different folder
from helpers import greet

# Right - specify the path
from utils.helpers import greet
```

**Circular imports**

```python
# file_a.py
from file_b import something

# file_b.py
from file_a import something_else  # Error!

# Solution: restructure your code
```


---

## Backlinks

The following sources link to this document:

- [Modules Guide](/resources/resources.index.llm.md)
- [Modules](/unit-2/projects/04-oracle/oracle-handbook.guide.llm.md)
