| name | code-quality-pylint |
| description | Master Pylint usage for maintaining high code quality in the Agent Operating System (AOS) repository. Includes static code analysis, error detection, PEP 8 enforcement, and code quality metrics. |
Skill: Code Quality with Pylint
Skill Overview
Purpose: Master Pylint usage for maintaining high code quality in the Agent Operating System (AOS) repository.
When to use:
- Before committing code changes
- During code review
- When debugging quality issues
- When refactoring code
- As part of CI/CD pipeline
Prerequisites:
- Python 3.10+ installed
- Repository dependencies installed (
pip install -e ".[dev]")
- Basic understanding of Python syntax and PEP 8
Core Knowledge
What is Pylint?
Pylint is a static code analysis tool that:
- Detects errors: Syntax errors, logic errors, and potential bugs
- Enforces standards: PEP 8 style guide and best practices
- Finds code smells: Duplicated code, unused variables, complex functions
- Provides metrics: Code quality scores and detailed reports
AOS Pylint Configuration
The repository uses a comprehensive Pylint configuration in pyproject.toml optimized for:
- Async Python: Handles async/await patterns correctly
- Azure Services: Understands Azure SDK patterns
- Agent Architecture: Tailored for perpetual agents and event-driven code
- Type Safety: Encourages type hints and modern Python
Step-by-Step Procedures
Procedure 1: Run Pylint Locally
Goal: Check code quality before committing
Steps:
-
Install Pylint (if not already installed):
cd /home/runner/work/AgentOperatingSystem/AgentOperatingSystem
pip install -e ".[dev]"
-
Run on entire source:
pylint src/AgentOperatingSystem
-
Run on specific module:
pylint src/AgentOperatingSystem/agents
pylint src/AgentOperatingSystem/orchestration
-
Run on single file:
pylint src/AgentOperatingSystem/agents/perpetual_agent.py
-
Review results:
- Look for E (Error): Critical issues that must be fixed
- Look for W (Warning): Important issues that should be fixed
- Look for C (Convention): Style issues (informational)
- Look for R (Refactor): Code structure suggestions
Expected outcome: Pylint report showing issues and overall score.
Procedure 2: Fix Common Pylint Issues
Goal: Resolve typical Pylint warnings in AOS code
Common Issues and Fixes:
Issue 1: Missing Type Hints
Pylint message: missing-type-arg, no-type-hint
async def process_event(self, event):
return await self.handle(event)
from typing import Any
async def process_event(self, event: dict) -> Any:
return await self.handle(event)
Issue 2: Unused Imports
Pylint message: unused-import
import asyncio
import logging
from typing import Dict
async def task():
await asyncio.sleep(1)
import asyncio
import logging
async def task():
await asyncio.sleep(1)
Issue 3: Undefined Variables
Pylint message: undefined-variable
async def get_status():
return agent_status
async def get_status(agent_id: str) -> dict:
agent_status = await fetch_status(agent_id)
return agent_status
Issue 4: Broad Exception Catching
Pylint message: broad-exception-caught
try:
await azure_operation()
except Exception as e:
logger.error(f"Error: {e}")
try:
await azure_operation()
except (ConnectionError, TimeoutError) as e:
logger.error(f"Azure connection error: {e}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
raise
Issue 5: Too Many Arguments
Pylint message: too-many-arguments
async def create_agent(
self, id, name, purpose, scope, criteria, adapter, config, metadata
):
pass
from dataclasses import dataclass
@dataclass
class AgentConfig:
id: str
name: str
purpose: str
scope: str
criteria: list
adapter: str
metadata: dict
async def create_agent(self, config: AgentConfig) -> Agent:
pass
Procedure 3: Generate and Review Pylint Reports
Goal: Create detailed quality reports for analysis
Steps:
-
Generate text report:
pylint src/AgentOperatingSystem --output-format=text > pylint-report.txt
-
Generate JSON report (for programmatic analysis):
pylint src/AgentOperatingSystem --output-format=json > pylint-report.json
-
Generate colorized console output:
pylint src/AgentOperatingSystem --output-format=colorized
-
Get only the score:
pylint src/AgentOperatingSystem --score-only
-
Review report sections:
- Messages by category: Groups issues by type
- Statistics by type: Counts of each issue
- Raw metrics: Lines of code, comments, etc.
- Global evaluation: Overall score and rating
Procedure 4: Fix Critical Issues in AOS Codebase
Goal: Address high-priority Pylint findings
Priority Levels:
-
Critical (Must Fix):
- Syntax errors
- Undefined variables
- Import errors
- Logic errors
-
High Priority (Should Fix):
- Unused variables
- Redefined names
- Dangerous default values
- Missing awaits on async functions
-
Medium Priority (Consider Fixing):
- Complex functions (too many branches)
- Long functions
- Unused imports
-
Low Priority (Optional):
- Line length (if < 150 chars)
- Missing docstrings (handled by code review)
- Naming convention variations
Fixing workflow:
-
Run Pylint and save output:
pylint src/AgentOperatingSystem > issues.txt
-
Filter for critical issues:
grep "E:" issues.txt
-
Fix issues one by one:
- Open the file mentioned
- Locate the line number
- Apply the fix
- Re-run Pylint on that file
-
Verify fix:
pylint src/AgentOperatingSystem/path/to/fixed_file.py
Procedure 5: Integrate with GitHub Copilot
Goal: Use Copilot to assist with Pylint compliance
Copilot Prompts for Quality:
async def my_function():
pass
async def process(self, data):
pass
async def complex_function():
pass
import sys
from azure.identity import DefaultAzureCredential
import asyncio
from typing import Dict
Using Copilot Chat:
- Select problematic code
- Open Copilot Chat
- Ask: "What Pylint issues does this have and how can I fix them?"
- Review suggestions
- Apply fixes
Procedure 6: Suppress Pylint Warnings (When Necessary)
Goal: Temporarily disable warnings when you have a good reason
When to suppress:
- False positives
- Third-party code patterns
- Temporary workarounds
- Intentional design decisions
How to suppress:
result = risky_call()
async def complex_function(arg1, arg2, arg3, arg4, arg5, arg6):
pass
Best practice: Always add a comment explaining why you're suppressing.
Common Patterns in AOS
Pattern 1: Async Agent Methods
from typing import Dict, Any, Optional
class MyAgent(PurposeDrivenAgent):
async def initialize(self) -> None:
"""Initialize agent resources."""
await super().initialize()
self.state: Dict[str, Any] = {}
async def process_event(
self,
event: Dict[str, Any],
timeout: Optional[int] = None
) -> Dict[str, Any]:
"""Process event with optional timeout."""
result: Dict[str, Any] = {}
return result
Pattern 2: Azure Service Integration
from typing import Optional
from azure.identity import DefaultAzureCredential
class AzureServiceManager:
def __init__(
self,
credential: Optional[DefaultAzureCredential] = None
) -> None:
self.credential = credential or DefaultAzureCredential()
async def connect(self) -> bool:
"""Connect to Azure service."""
try:
return True
except ConnectionError as exc:
logger.error("Connection failed: %s", exc)
return False
Pattern 3: Error Handling with Logging
import logging
from typing import Any
logger = logging.getLogger(__name__)
async def safe_operation(data: Any) -> bool:
"""Perform operation with comprehensive error handling."""
try:
await risky_operation(data)
return True
except ValueError as exc:
logger.warning("Invalid data: %s", exc)
return False
except ConnectionError as exc:
logger.error("Connection lost: %s", exc)
raise
except Exception as exc:
logger.exception("Unexpected error: %s", exc)
return False
Troubleshooting
Issue: "Import error" for git-based dependencies
Symptom: Pylint complains about imports from LeadershipAgent or PurposeDrivenAgent
Solution: These are disabled in config. If needed:
from LeadershipAgent import LeadershipAgent
Issue: "No member" errors for Azure SDK
Symptom: Pylint doesn't recognize Azure SDK attributes
Solution: Already configured in pyproject.toml with ignore-on-opaque-inference. If still occurs:
azure_client.dynamic_property
Issue: Score too low
Symptom: Pylint score below 5.0, failing CI/CD
Solution:
- Focus on errors (E) first
- Then warnings (W)
- Document remaining issues
- Consider if score threshold needs adjustment
Issue: Too many warnings to fix at once
Symptom: Hundreds of warnings, overwhelming
Solution:
- Run on specific modules:
pylint src/AgentOperatingSystem/agents
- Filter by severity:
pylint src | grep "E:"
- Fix incrementally, one module at a time
- Track progress in issues/PRs
Integration with Development Workflow
Daily Development
- Before coding: Review Pylint configuration
- During coding: Use Copilot for quality suggestions
- After coding: Run Pylint on changed files
- Before commit: Run Pylint on affected modules
- In PR: Review CI/CD Pylint results
Code Review Checklist
Resources
- Pylint Documentation: https://pylint.readthedocs.io/
- AOS Code Quality Instructions:
.github/instructions/code-quality.instructions.md
- Pylint Configuration:
pyproject.toml ([tool.pylint.*] sections)
- GitHub Workflow:
.github/workflows/pylint.yml
Quick Command Reference
pylint src/AgentOperatingSystem
pylint tests
pylint function_app.py
pylint src/AgentOperatingSystem/agents
pylint src/AgentOperatingSystem/orchestration
pylint src/AgentOperatingSystem/mcp
pylint src --fail-under=5.0
pylint src --score-only
pylint src --output-format=json > report.json
pip install -e ".[dev]"
pip install --upgrade pylint
Success Criteria
You've mastered this skill when you can:
Next Steps:
- Practice running Pylint on small code sections
- Fix one category of issues at a time
- Review CI/CD Pylint results regularly
- Share learnings with the team