Skill Details
Runtime
(claude-5-sonnet)
Example user message
[userMessage]: Legacy Code: import urllib2 def fetch_data(url): try: response = urllib2.urlopen(url) print "Data fetched successfully!" return response.read() except urllib2.URLError, e: print "Error fetching data: " + str(e) Original Language/Version: Python 2.7 Target Language/Version: Python 3.11+
Example agent response
🛠️ Refactor Summary
Migration: Python 2.7 ➡️ Python 3.11+
Key Improvements:
Replaced urllib2 with the modern urllib.request (and added an option to use requests as a more ergonomic alternative)
Converted print statements to function calls and modernized exception syntax (except X as e)
Added timeout handling, input validation, HTTP status checking, and specific exception branches (network vs. HTTP errors) with proper logging instead of bare print
💻 Modernized Code
python
"""
Module for fetching remote data over HTTP(S).
Migrated from Python 2.7's urllib2 to Python 3.11+'s urllib.request.
"""
import logging
import urllib.request
import urllib.error
logger = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 10 # seconds
def fetch_data(url: str, timeout: float = DEFAULT_TIMEOUT) -> bytes:
"""
Fetch raw data from the given URL.
Args:
url: The HTTP/HTTPS URL to fetch.
timeout: Number of seconds to wait before giving up.
Returns:
The response body as bytes.
Raises:
ValueError: If the URL is empty or not a string.
urllib.error.URLError: If the request fails at the network/connection level.
urllib.error.HTTPError: If the server returns a non-2xx status code.
"""
if not isinstance(url, str) or not url.strip():
raise ValueError("url must be a non-empty string")
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
status = getattr(response, "status", 200)
if status >= 400:
# Defensive check; urlopen normally raises HTTPError itself,
# but this guards against unexpected implementations.
raise urllib.error.HTTPError(
url, status, "Non-success status code", response.headers, None
)
data = response.read()
logger.info("Data fetched successfully from %s (%d bytes)", url, len(data))
return data
except urllib.error.HTTPError as e:
# Server responded, but with an error status (4xx/5xx)
logger.error("HTTP error fetching %s: %s (status %s)", url, e.reason, e.code)
raise
except urllib.error.URLError as e:
# Network-level failure (DNS, connection refused, timeout, etc.)
logger.error("Error fetching data from %s: %s", url, e.reason)
raise
Notes on the refactor:
urllib2.urlopen(url) ➜ urllib.request.urlopen(url, timeout=...) — added a timeout so the call can't hang forever, which was a latent risk in the original.
except urllib2.URLError, e: (Python 2 comma syntax) ➜ except urllib.error.URLError as e: (Python 3 syntax), split into HTTPError (subclass of URLError) and URLError branches so HTTP status errors and network errors are handled/logged distinctly.
Swapped print for logging calls so output is leveled, timestamped, and redirectable — standard practice for production-quality code instead of legacy debug prints.
Added a docstring and an input-validation guard (raise ValueError on bad input) that the original lacked entirely.
If you'd like, I can also show a requests-based version, which is the more idiomatic third-party choice for HTTP calls in modern Python codebases these days.
By purchasing this skill, you agree to our terms of service
CLAUDE-5-SONNET
Tackle technical debt instantly with the Legacy Code Modernizer. This Claude skill transforms outdated code (like Python 2.x or ES5) into clean, modern, and idiomatic syntax. It goes beyond simple translation by automatically implementing robust error handling, modern best practices, and comprehensive documentation. Perfect for developers looking to future-proof projects, eliminate vulnerabilities, and save hours on manual refactoring.
...more
Added 4 weeks ago
