import os
import sys
from typing import List, Dict, Optional, Any
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Person:
name: str
age: int
email: Optional[str] = None
def __post_init__(self):
if self.age < 0:
raise ValueError("Age cannot be negative")
def greet(self) -> str:
return f"Hello, my name is {self.name} and I'm {self.age} years old."
class DatabaseManager:
def __init__(self, connection_string: str):
self.connection = connection_string
self._cache: Dict[str, Any] = {}
self.is_connected = False
async def connect(self) -> bool:
try:
print(f"Connecting to: {self.connection}")
self.is_connected = True
return True
except ConnectionError as e:
print(f"Failed to connect: {e}")
return False
finally:
print("Connection attempt completed")
def query(self, sql: str, params: Optional[List[str]] = None) -> Dict:
if not self.is_connected:
raise RuntimeError("Not connected to database")
cache_key = f"query_{hash(sql)}_{hash(str(params))}"
if cache_key in self._cache:
print("Cache hit!")
return self._cache[cache_key]
cleaned_params = [p.strip() for p in (params or []) if p]
result = {
"sql": sql,
"params": cleaned_params,
"timestamp": datetime.now().isoformat(),
"rows_affected": len(cleaned_params),
}
self._cache[cache_key] = result
return result
def process_data(items: List[Dict[str, Any]]) -> List[str]:
results = []
for i, item in enumerate(items):
if (value := item.get("value")) is not None:
match item.get("type"):
case "string":
processed = f"String: {value.upper()}"
case "number":
processed = f"Number: {value * 2}"
case "boolean":
processed = f"Boolean: {not value}"
case _:
processed = f"Unknown: {value}"
results.append(f"Item {i}: {processed}")
else:
error_msg = """
Error: Item missing required 'value' field.
This is a multi-line string to demonstrate
syntax highlighting for different string types.
"""
print(error_msg.strip())
return results
def main():
pattern = r"^\d{3}-\d{2}-\d{4}$"
config = {
"debug": True,
"max_retries": 3,
"timeout": 30.5,
"endpoints": ["api.example.com", "backup.example.com"],
"credentials": None,
"pattern": pattern,
}
person = Person("Alice", 30, "alice@example.com")
db = DatabaseManager("postgresql://localhost:5432/mydb")
sample_data = [
{"type": "string", "value": "hello world"},
{"type": "number", "value": 42},
{"type": "boolean", "value": True},
{"type": "unknown", "value": [1, 2, 3]},
{"type": "string"}, ]
try:
results = process_data(sample_data)
for result in results:
print(result)
except Exception as e:
print(f"Error processing data: {e}")
output_file = "demo_output.txt"
with open(output_file, "w") as f:
f.write("# Demo Output\n")
f.write(f"Generated at: {datetime.now()}\n")
f.write(f"Person: {person.greet()}\n")
squared = (x**2 for x in range(10) if x % 2 == 0)
f.write(f"Even squares: {list(squared)}\n")
print(f"Output written to {output_file}")
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--help":
print(__doc__)
sys.exit(0)
main()