Examples

This section demonstrates autopep723 usage with real examples from the project.

Simple Demo (No Dependencies)

A basic script that uses only built-in Python modules:

 1#!/usr/bin/env python3
 2
 3import json
 4import os
 5import sys
 6from datetime import datetime
 7from pathlib import Path
 8
 9
10def main():
11    """Simple demo script that works without external dependencies."""
12
13    print("🎯 autopep723 Demo Script")
14    print("=" * 40)
15
16    # Show system info
17    print(f"Python version: {sys.version}")
18    print(f"Current directory: {os.getcwd()}")
19    print(f"Script path: {Path(__file__).absolute()}")
20    print(f"Current time: {datetime.now().isoformat()}")
21
22    # Create some sample data
23    data = {
24        "demo": "autopep723",
25        "timestamp": datetime.now().isoformat(),
26        "python_version": sys.version_info[:3],
27        "features": [
28            "Automatic dependency detection",
29            "PEP 723 metadata generation",
30            "Import name mapping",
31            "File update capability",
32            "Direct script execution",
33        ],
34    }
35
36    # Display the data
37    print("\n📊 Demo Data:")
38    print(json.dumps(data, indent=2))
39
40    # Test some built-in module functionality
41    print("\n🔧 Testing built-in modules:")
42
43    # Test pathlib
44    current_file = Path(__file__)
45    print(f"✓ pathlib: {current_file.name} ({current_file.stat().st_size} bytes)")
46
47    # Test json
48    json_str = json.dumps({"test": "data"})
49    print(f"✓ json: Serialized {len(json_str)} characters")
50
51    # Test datetime
52    now = datetime.now()
53    print(f"✓ datetime: {now.strftime('%Y-%m-%d %H:%M:%S')}")
54
55    # Test os
56    env_count = len(os.environ)
57    print(f"✓ os: Found {env_count} environment variables")
58
59    print("\n✅ All tests completed successfully!")
60    print("\nThis script demonstrates autopep723 with a script that:")
61    print("  - Uses only built-in Python modules")
62    print("  - Should generate empty dependencies list")
63    print("  - Can be run without any external packages")
64    print("\nTry running:")
65    print("  autopep723 examples/simple_demo.py")
66    print("  autopep723 add examples/simple_demo.py")
67    print("  autopep723 check examples/simple_demo.py")
68
69
70if __name__ == "__main__":
71    main()

Usage:

# Check what dependencies would be detected (should be empty)
autopep723 check examples/simple_demo.py

# Run the script
autopep723 examples/simple_demo.py

Web Scraper

A script that uses external packages (requests and beautifulsoup4):

 1#!/usr/bin/env python3
 2
 3import json
 4import time
 5from urllib.parse import urljoin
 6
 7import requests
 8from bs4 import BeautifulSoup
 9
10
11def scrape_website(url):
12    """Simple web scraper example using requests and BeautifulSoup."""
13
14    # Make request with headers to avoid being blocked
15    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
16
17    try:
18        response = requests.get(url, headers=headers, timeout=10)
19        response.raise_for_status()
20
21        # Parse HTML content
22        soup = BeautifulSoup(response.content, "html.parser")
23
24        # Extract basic information
25        title = soup.find("title")
26        title_text = title.get_text().strip() if title else "No title found"
27
28        # Find all links
29        links = []
30        for link in soup.find_all("a", href=True):
31            href = link["href"]
32            absolute_url = urljoin(url, href)
33            link_text = link.get_text().strip()
34            if link_text:
35                links.append({"url": absolute_url, "text": link_text})
36
37        # Extract meta description
38        meta_desc = soup.find("meta", attrs={"name": "description"})
39        description = meta_desc.get("content", "") if meta_desc else ""
40
41        return {
42            "url": url,
43            "title": title_text,
44            "description": description,
45            "links_count": len(links),
46            "links": links[:10],  # First 10 links only
47            "scraped_at": time.time(),
48        }
49
50    except requests.RequestException as e:
51        print(f"Error scraping {url}: {e}")
52        return None
53
54
55def main():
56    """Main function to demonstrate the scraper."""
57
58    # Example URLs to scrape
59    urls = [
60        "https://httpbin.org/html",
61        "https://example.com",
62    ]
63
64    results = []
65
66    for url in urls:
67        print(f"Scraping: {url}")
68        result = scrape_website(url)
69
70        if result:
71            results.append(result)
72            print(f"✓ Title: {result['title']}")
73            print(f"✓ Links found: {result['links_count']}")
74        else:
75            print("✗ Failed to scrape")
76
77        # Be polite to servers
78        time.sleep(1)
79
80    # Save results to JSON file
81    with open("scrape_results.json", "w") as f:
82        json.dump(results, f, indent=2)
83
84    print("\nScraping complete! Results saved to scrape_results.json")
85    print(f"Total sites scraped: {len(results)}")
86
87
88if __name__ == "__main__":
89    main()

Usage:

# Check detected dependencies
autopep723 check examples/web_scraper.py

# Update file with PEP 723 metadata
autopep723 add examples/web_scraper.py

# Run with automatic dependency management
autopep723 examples/web_scraper.py

Expected dependencies:

  • requests - HTTP library

  • beautifulsoup4 - HTML parsing (from bs4 import)

Shebang Example

Demonstrates using autopep723 as a shebang for executable scripts:

 1#!/usr/bin/env autopep723
 2import json
 3from datetime import datetime
 4
 5import requests
 6
 7
 8def main():
 9    """Example script that demonstrates shebang usage with autopep723."""
10
11    print("🚀 Shebang Example Script")
12    print("=" * 40)
13    print("This script demonstrates using autopep723 as a shebang!")
14    print()
15
16    # Make a simple HTTP request
17    try:
18        print("📡 Making HTTP request to httpbin.org...")
19        response = requests.get("https://httpbin.org/json", timeout=10)
20        response.raise_for_status()
21
22        data = response.json()
23        print("✅ Request successful!")
24        print(f"Response data: {json.dumps(data, indent=2)}")
25
26    except requests.RequestException as e:
27        print(f"❌ Request failed: {e}")
28        return 1
29
30    print()
31    print("🎯 Key Points:")
32    print("  - This script uses '#!/usr/bin/env autopep723' as shebang")
33    print("  - autopep723 automatically detected 'requests' dependency")
34    print("  - The script runs with: uv run --with requests script.py")
35    print("  - No need to manually declare PEP 723 metadata!")
36
37    print()
38    print(f"⏰ Executed at: {datetime.now().isoformat()}")
39
40    return 0
41
42
43if __name__ == "__main__":
44    exit(main())

Usage:

# Make executable and run directly
chmod +x examples/shebang_example.py
./examples/shebang_example.py

The shebang #!/usr/bin/env autopep723 automatically:

  1. Detects the requests dependency

  2. Creates an isolated environment

  3. Installs required packages

  4. Executes the script

For uvx usage, change the shebang to:

#!/usr/bin/env -S uvx autopep723

Machine Learning Analysis

A comprehensive data science script with multiple dependencies:

 1#!/usr/bin/env python3
 2# /// script
 3# requires-python = ">=3.13"
 4# dependencies = [
 5#     "matplotlib",
 6#     "pandas",
 7#     "scikit-learn",
 8#     "seaborn",
 9# ]
10# ///
11
12
13import matplotlib.pyplot as plt
14import pandas as pd
15import seaborn as sns
16from sklearn.datasets import make_classification
17from sklearn.ensemble import RandomForestClassifier
18from sklearn.metrics import classification_report, confusion_matrix
19from sklearn.model_selection import train_test_split
20from sklearn.preprocessing import StandardScaler

This example already includes PEP 723 metadata and demonstrates:

  • Data generation and exploration

  • Visualization with matplotlib/seaborn

  • Machine learning with scikit-learn

  • Data manipulation with pandas

Usage:

# Run the complete analysis
autopep723 examples/ml_analysis.py

Dependencies included:

  • matplotlib - Plotting library

  • pandas - Data manipulation

  • scikit-learn - Machine learning (from sklearn import)

  • seaborn - Statistical visualization

Import Name Mappings

These examples showcase how autopep723 handles import name mappings:

Script Import

Detected Package

Reason

from bs4 import BeautifulSoup

beautifulsoup4

Import name differs from package

from sklearn import datasets

scikit-learn

Common alias mapping

import requests

requests

Direct mapping

import matplotlib.pyplot

matplotlib

Top-level package detection

Testing the Examples

Run all examples to see autopep723 in action:

# Check all examples
for script in examples/*.py; do
    echo "=== $script ==="
    autopep723 check "$script"
    echo
done

# Run all examples (be patient with ML example!)
for script in examples/*.py; do
    echo "Running $script..."
    autopep723 "$script"
done

Creating Your Own Scripts

Based on these examples, follow this pattern:

  1. Write your script with normal import statements

  2. Test detection: autopep723 check script.py

  3. Add metadata: autopep723 add script.py

  4. Make executable (optional): Add shebang and chmod +x

The tool handles the complexity of dependency management automatically!