Documentation
Languages and Frameworks/Python

Python Support

ThinkCode provides robust support for Python development, offering specialized tools and AI-powered features designed to enhance productivity, code quality, and development efficiency.

Getting Started

Installation and Setup

ThinkCode automatically detects Python projects. For optimal experience:

  1. Install Python Extension:

    • ThinkCode will prompt to install the Python extension when you open a Python file
    • Alternatively, open the Extensions view (Ctrl+Shift+X / Cmd+Shift+X) and search for "ThinkCode Python"
  2. Select Python Interpreter:

    • Command Palette (Ctrl+Shift+P / Cmd+Shift+P)
    • Type "ThinkCode: Select Interpreter"
    • Choose from available Python environments
  3. Project Configuration:

    • ThinkCode supports standard configuration files:
      • pyproject.toml - Modern Python project configuration
      • setup.py / setup.cfg - Package configuration
      • requirements.txt - Dependency specifications
      • .env - Environment variables
  4. Create a New Project:

    • Command Palette
    • Type "ThinkCode: Create New Project"
    • Select Python from template categories

IntelliSense and Code Navigation

Code Intelligence

ThinkCode provides advanced intelligence for Python:

  • Type Inference: Automatic type detection with support for:

    • Runtime type checking
    • Type annotations (PEP 484)
    • Type comments
    • Stub files (.pyi)
  • Auto-Completion: Context-aware suggestions for:

    • Variables, functions, and classes
    • Module imports
    • Function parameters with type hints
    • docstring parameters

Example of Python type hints:

def greeting(name: str, age: int = None) -> str:
    """Generate a greeting message.
    
    Args:
        name: The person's name
        age: The person's age (optional)
        
    Returns:
        A personalized greeting string
    """
    if age is not None:
        return f"Hello {name}, you are {age} years old!"
    return f"Hello {name}!"
 
# ThinkCode shows proper completion and type checking
result = greeting("Alice", "42")  # Error: Argument of type 'str' cannot be assigned to parameter 'age' of type 'int'

Smart Navigation

Navigate your codebase efficiently:

  • Go to Definition: Jump to symbol definitions

    • Keyboard: F12 or Ctrl+Click / Cmd+Click
    • Works across virtual environments and packages
  • Find All References: Locate all usages of a symbol

    • Keyboard: Shift+F12
  • Peek Definition: View definitions without leaving current file

    • Keyboard: Alt+F12
  • Symbol Navigation:

    • File symbols: Ctrl+Shift+O / Cmd+Shift+O
    • Workspace symbols: Ctrl+T / Cmd+T
  • Import Management:

    • Auto-organize imports
    • Remove unused imports
    • Add missing imports

AI-Powered Development Features

Code Generation

Generate Python code with natural language prompts:

  1. Function Generation:

    • Add a comment describing function purpose
    • Press Alt+I / Option+I for AI implementation

    Example:

    # Generate a function that calculates the Fibonacci sequence up to n
    # Press Alt+I here and ThinkCode generates the implementation
    def fibonacci(n: int) -> list[int]:
        """
        Generate Fibonacci sequence up to n.
        
        Args:
            n: Upper bound for the sequence
            
        Returns:
            List of Fibonacci numbers up to n
        """
        if n <= 0:
            return []
        if n == 1:
            return [0]
        
        fib = [0, 1]
        while fib[-1] + fib[-2] <= n:
            fib.append(fib[-1] + fib[-2])
        
        return fib
  2. Code Transformation:

    • Select code to transform
    • Open Command Palette
    • Type "ThinkCode: Transform Code"
    • Choose transformations like:
      • Convert function to class method
      • Transform to list comprehension
      • Optimize algorithm
  3. Test Generation:

    • Select function to test
    • Right-click and select "Generate Tests"
    • ThinkCode analyzes function and generates pytest test cases

Refactoring

AI-assisted refactoring capabilities:

  • Smart Renaming: Intelligently rename variables, functions, and classes
  • Extract Method/Variable: Extract selections with proper parameters
  • Convert Syntax: Transform between code styles
    • Regular loops ↔ Comprehensions
    • Functions ↔ Classes
    • Synchronous ↔ Asynchronous

Customize refactoring settings:

{
  "thinkcode.python.refactoring": {
    "preferListComprehension": true,
    "preferTypeAnnotations": true,
    "codeStyle": "modern" // Options: "legacy", "modern", "functional"
  }
}

Documentation Assistant

Generate and maintain documentation:

  • Docstring Generation: Auto-generate comprehensive docstrings
    • Supports NumPy, Google, and reStructuredText styles
  • README Creation: Generate project documentation
  • API Documentation: Create API reference documentation

Example of AI-assisted documentation:

# Place cursor here and use Command Palette > "Generate Documentation"
def process_data(data: list, 
                 threshold: float = 0.5, 
                 normalize: bool = False, 
                 callback=None) -> dict:
    """
    Process data according to specified parameters.
    
    Parameters
    ----------
    data : list
        The input data to process
    threshold : float, optional
        Cutoff threshold for processing, by default 0.5
    normalize : bool, optional
        Whether to normalize the data, by default False
    callback : callable, optional
        Function to call after processing each item
        
    Returns
    -------
    dict
        A dictionary containing processed data and stats
        
    Raises
    ------
    ValueError
        If data is empty or threshold is negative
    TypeError
        If callback is provided but not callable
    
    Examples
    --------
    >>> process_data([1, 2, 3, 4, 5], threshold=2.0)
    {'processed': [0, 0, 1, 1, 1], 'stats': {'passed': 3, 'total': 5}}
    """
    # Implementation...

Environment Management

Virtual Environments

Seamlessly work with Python virtual environments:

  • Environment Detection: Automatic detection of:

    • venv / virtualenv
    • conda environments
    • pipenv
    • poetry
    • pyenv
  • Environment Creation:

    • Command Palette
    • Type "ThinkCode: Create Environment"
    • Choose environment type
  • Environment Switching:

    • Status bar indicator for active environment
    • Click to change environments

Package Management

Manage Python packages with integrated tools:

  • Dependency Visualization: View package dependency graphs
  • Package Installation: Install packages with inline UI
  • Requirements Management: Update and generate requirements files
  • Vulnerability Scanning: Identify and fix security issues

Access package management:

  1. Right-click on requirements.txt or pyproject.toml
  2. Select "Manage Python Packages"

Project Tools

Project Templates

Start new Python projects with specialized templates:

  • Web Applications: Flask, FastAPI, Django
  • Data Science: Jupyter, pandas, scikit-learn
  • CLI Applications: Click, Typer
  • API Services: RESTful, GraphQL

Access templates:

  1. Command Palette
  2. Type "ThinkCode: Create New Project"
  3. Select Python category

Project Structure

Manage your Python project structure:

  • Layout Visualization: Graphical view of project components
  • Best Practice Suggestions: Structure recommendations based on project type
  • Import Organization: Optimize import structures

Debugging and Testing

Debugging

Powerful Python debugging capabilities:

  • Launch Configurations: Preconfigured debug setups
  • Advanced Breakpoints:
    • Conditional breakpoints
    • Log points
    • Data breakpoints
  • Hot Reloading: Edit and continue debugging
  • Variable Inspection: Rich variable explorer

Example launch configuration:

// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Current File",
      "type": "thinkcode-python",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "justMyCode": false
    }
  ]
}

Testing

Integrated testing for Python:

  • Test Explorer: View and run tests with visual UI
  • Test Discovery: Automatic discovery for pytest, unittest
  • Coverage Visualization: Highlight code coverage inline
  • Parameterized Tests: Visual support for parameterized tests

Configure testing:

{
  "thinkcode.python.testing": {
    "enabled": true,
    "framework": "pytest", // Options: "pytest", "unittest"
    "autoTestDiscovery": true,
    "showCoverage": true
  }
}

Development Scenarios

Data Science and Machine Learning

Specialized tools for data science:

  • Notebook Integration: Work with Jupyter notebooks
  • Data Visualization: Preview pandas DataFrames and plots
  • Model Analysis: Inspect machine learning models
  • REPL Integration: Interactive Python console

Activate data science features:

{
  "thinkcode.python.datascience": {
    "enabled": true,
    "notebookSupport": true,
    "dataFramePreview": true,
    "autoPlotting": true
  }
}

Web Development

Support for Python web frameworks:

  • Django Intelligence: Template language support, URL routing
  • Flask/FastAPI: Route detection, OpenAPI integration
  • Template Support: Jinja2 and other template engines
  • RESTful API: Endpoint testing and documentation

Scientific Computing

Support for scientific libraries:

  • NumPy/SciPy: Array operation intelligence
  • Matplotlib/Plotly: Plot previews and suggestions
  • Pandas: DataFrame operations and optimizations
  • Performance Profiling: Identify computation bottlenecks

Code Quality and Analysis

Linting and Formatting

Integrated code quality tools:

  • Linting: Support for:

    • Ruff (recommended)
    • Pylint
    • Flake8
    • Mypy
  • Formatting: Support for:

    • Black
    • YAPF
    • autopep8
    • isort

Configure linting:

{
  "thinkcode.python.linting": {
    "enabled": true,
    "linter": "ruff", // Options: "ruff", "pylint", "flake8", "mypy"
    "severity": {
      "error": ["E", "F"],
      "warning": ["W", "C"],
      "information": ["D", "N"]
    }
  }
}

Code Analysis

Advanced code analysis features:

  • Static Analysis: Detect potential bugs and issues
  • Complexity Analysis: Cyclomatic complexity visualization
  • Performance Analysis: Identify performance bottlenecks
  • Best Practice Enforcement: PEP 8 and other Python standards

Security Analysis

Python-specific security scanning:

  • Vulnerability Detection: Find common Python vulnerabilities
  • Dependency Scanning: Check for vulnerable packages
  • Input Validation: Verify proper input handling
  • Code Injection Prevention: Detect potential injection points

Customization

Extension Points

Extend ThinkCode's Python support:

  • Custom Linters: Integrate specialized linting rules
  • Code Actions: Create custom code refactorings
  • Analyzers: Develop custom code analyzers
  • Language Servers: Configure custom language servers

Configuration Options

Comprehensive configuration for Python development:

{
  "thinkcode.python": {
    "formatting": {
      "provider": "black",
      "lineLength": 88,
      "formatOnSave": true
    },
    "analysis": {
      "typeCheckingMode": "basic", // Options: "off", "basic", "strict"
      "extraPaths": [],
      "diagnosticMode": "workspace",
      "autoImportCompletions": true
    },
    "terminal": {
      "activateEnvironment": true,
      "launchArgs": [],
      "executeInFileDir": true
    }
  }
}

Resources and Learning

Learning Paths

Integrated learning resources:

  • Interactive Tutorials: Learn Python concepts
  • Code Challenges: Practice with hands-on exercises
  • Sample Projects: Explore and learn from example projects
  • Best Practice Guides: Context-sensitive coding guidelines

Access learning resources:

  1. Command Palette
  2. Type "ThinkCode: Open Learning Hub"
  3. Select Python category

Community Integration

Connect with the Python community:

  • Documentation: Access Python documentation inline
  • Library Examples: View usage examples from popular libraries
  • Stack Overflow: Search solutions directly from ThinkCode
  • Resource Recommendations: Get intelligent suggestions for learning resources

Framework-Specific Features

Django Support

Specialized tools for Django development:

  • Project Navigation: Navigate between models, views, templates
  • ORM Intelligence: Smart completions for querysets and models
  • Template Support: Syntax highlighting and completions
  • URL Routing: Jump between URLs and views

Flask/FastAPI Support

Focused features for API development:

  • Route Detection: Map endpoints to handler functions
  • Swagger Integration: Preview and test API endpoints
  • Request/Response Validation: Verify input/output schemas
  • Middleware Visualization: View middleware execution order

Data Science Frameworks

Specialized support for data science libraries:

  • NumPy/Pandas: Array and DataFrame operations
  • Scikit-learn: ML model intelligence and debugging
  • TensorFlow/PyTorch: Model architecture visualization
  • Visualization Libraries: Preview plots and charts

Performance Tuning

Performance Analysis

Identify and fix performance issues:

  • Profile Visualization: View CPU and memory profiles
  • Bottleneck Detection: Find slow code sections
  • Memory Analysis: Track memory usage and leaks
  • Optimization Suggestions: AI-powered performance tips

Access performance tools:

  1. Command Palette
  2. Type "ThinkCode: Analyze Python Performance"

Optimization Suggestions

Get intelligent suggestions for improving performance:

  • Algorithm Alternatives: More efficient algorithm suggestions
  • Data Structure Optimization: Better data structure choices
  • Parallelization Opportunities: Multi-threading/processing hints
  • C Extension Usage: When to use compiled extensions

Further Information