code-style

Руководство по запуску линтеров и форматтеров кода. Используйте это, когда вас просят проверить стиль кода, запустить линтеры или исправить проблемы с форматированием.

npx skills add https://github.com/microsoft/semantic-link-labs --skill code-style

Code Style and Linting

This skill covers code style checking and formatting workflows for the Semantic Link Labs project.

When to Use This Skill

Use this skill when you need to:

  • Check code for style violations
  • Format code with black
  • Verify type correctness with mypy
  • Fix linting errors before committing
  • Ensure code follows project standards

Formatting Tools

ToolPurposeConfiguration
blackCode formattingpyproject.toml
flake8Style checkingpyproject.toml
mypyType checkingpyproject.toml

Code Formatting with Black

The project uses black for code formatting.

Running Black

# Format all source files
black src/sempy_labs tests

# Check without modifying (dry run)
black --check src/sempy_labs tests

# Show diff of changes
black --diff src/sempy_labs tests

# Format specific file
black src/sempy_labs/_workspaces.py

Black Configuration

From pyproject.toml, max line length is configured via flake8 settings.


Style Checking with Flake8

Running Flake8

# Check all source files
flake8 src/sempy_labs tests

# Check specific file
flake8 src/sempy_labs/_helper_functions.py

# Show source code for each error
flake8 --show-source src/sempy_labs

# Show statistics summary
flake8 --statistics src/sempy_labs

Flake8 Configuration

From pyproject.toml:

[tool.flake8]
max-line-length = 200

Common Flake8 Errors

CodeDescriptionFix
E501Line too long (>200 chars)Break line or shorten code
F401Imported but unusedRemove unused import
F841Variable assigned but never usedRemove or use the variable
E302Expected 2 blank linesAdd blank lines between functions
E303Too many blank linesRemove extra blank lines
W291Trailing whitespaceRemove trailing spaces
E711Comparison to NoneUse is None instead of == None

Type Checking with Mypy

Running Mypy

# Check all source files
mypy src/sempy_labs

# Check specific file
mypy src/sempy_labs/_workspaces.py

# Show error codes
mypy --show-error-codes src/sempy_labs

Mypy Configuration

From pyproject.toml:

[[tool.mypy.overrides]]
module = "sempy.*,Microsoft.*,System.*,anytree.*,synapse.ml.services.*,polib.*,jsonpath_ng.*,anywidget.*,sqlglot.*"
ignore_missing_imports = true

Common Mypy Errors

ErrorDescriptionFix
Incompatible typesType mismatchFix type annotation or value
Missing return statementFunction missing returnAdd return statement
Argument has incompatible typeWrong argument typePass correct type
has no attributeAttribute doesn't existCheck spelling or type

Adding Type Ignore Comments

When mypy raises false positives:

# Ignore specific error
result = some_function()  # type: ignore[return-value]

# Ignore all errors on line
result = some_function()  # type: ignore

Import Organization

Import Order

Organize imports in this order (with blank lines between groups):

  1. Standard library imports
  2. Third-party imports
  3. Local application imports

Example Import Structure

# Standard library
import os
import json
from typing import Optional, List
from uuid import UUID

# Third-party
import pandas as pd
import requests

# Semantic Link (dependency)
import sempy.fabric as fabric
from sempy._utils._log import log

# Local imports
import sempy_labs._icons as icons
from sempy_labs._helper_functions import (
    resolve_workspace_id,
    _base_api,
)

Pre-Commit Style Checklist

Before committing code changes:

# Format code
black src/sempy_labs tests

# Check for style issues
flake8 src/sempy_labs tests

# Check types (optional)
mypy src/sempy_labs

# If any errors, fix and re-run

Common Style Fixes

Line Too Long

Break long lines using parentheses or backslash:

# Before
result = some_very_long_function_call(parameter1, parameter2, parameter3, parameter4, parameter5)

# After
result = some_very_long_function_call(
    parameter1,
    parameter2,
    parameter3,
    parameter4,
    parameter5
)

F-String Line Breaks

# Before
print(f"{icons.green_dot} The '{item_name}' {item_type} has been successfully created in the '{workspace_name}' workspace.")

# After (if too long)
print(
    f"{icons.green_dot} The '{item_name}' {item_type} has been successfully "
    f"created in the '{workspace_name}' workspace."
)

Dictionary Formatting

# Before
payload = {"displayName": name, "description": description, "definition": definition}

# After
payload = {
    "displayName": name,
    "description": description,
    "definition": definition,
}

IDE Integration

VS Code Settings

Recommended .vscode/settings.json:

{
    "python.formatting.provider": "black",
    "python.linting.flake8Enabled": true,
    "python.linting.mypyEnabled": true,
    "editor.formatOnSave": true,
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter"
    }
}

Больше skills от microsoft

oss-growth
microsoft
Персона OSS-хакера роста
agent-framework-azure-ai-py
microsoft
Создание агентов Azure AI Foundry с использованием Microsoft Agent Framework Python SDK (agent-framework-azure-ai). Используйте при создании постоянных агентов с AzureAIAgentsProvider, применении размещенных инструментов (интерпретатор кода, поиск файлов, веб-поиск), интеграции MCP-серверов, управлении потоками бесед или реализации потоковых ответов. Охватывает функциональные инструменты, структурированные выходные данные и агентов с несколькими инструментами.
development
airunway-aks-setup
microsoft
Настройка AI Runway на AKS — от пустого кластера до работающей модели. Охватывает проверку кластера, установку контроллера, оценку GPU, настройку провайдера и первое развертывание. КОГДА: «настроить AI Runway», «подключить кластер AKS», «установить AI Runway», «airunway setup», «развернуть модель на AKS», «GPU-инференс на AKS», «настройка KAITO на AKS», «запуск LLM на AKS», «vLLM на AKS», «настройка обслуживания моделей на AKS», «контроллер AI Runway».
devops
appinsights-instrumentation
microsoft
Guidance for instrumenting webapps with Azure Application Insights. Provides telemetry patterns, SDK setup, and configuration references. WHEN: how to instrument app, App Insights SDK, telemetry patterns, what is App Insights, Application Insights guidance, instrumentation examples, APM best practices.
devops
applicationinsights-web-ts
microsoft
Инструментируйте браузерные/веб-приложения с помощью JavaScript SDK Application Insights (@microsoft/applicationinsights-web). Используйте для мониторинга реальных пользователей (RUM) — просмотры страниц, клики, зависимости AJAX/fetch, исключения, пользовательские события и трассировки агентов GenAI на стороне браузера, коррелируемые с бэкенд-трассировками OpenTelemetry. Охватывает скрипт загрузчика SDK и настройку npm, расширения фреймворков (React, React Native, Angular), Click Analytics, инициализаторы телеметрии и семантические конвенции OTel GenAI для спанов агента/инструмента/модели, генерируемых из браузера.
devops
azure-ai-anomalydetector-java
microsoft
Создавайте приложения для обнаружения аномалий с помощью Azure AI Anomaly Detector SDK для Java. Используйте при реализации одномерного/многомерного обнаружения аномалий, анализа временных рядов или мониторинга на основе ИИ.
development
azure-ai-language-conversations-py
microsoft
Реализация понимания разговорного языка (CLU) с использованием Python SDK azure-ai-language-conversations. Используйте при работе с ConversationAnalysisClient для анализа намерений и сущностей в разговоре, создании NLP-функций или интеграции языкового понимания в приложения.
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 для Python. Используется для рабочих областей ML, заданий, моделей, наборов данных, вычислений и конвейеров. Триггеры: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets".
development