Skip to main content

Improved Python SDK Code Quality and Language Alignment

· 10 min read

This release delivers comprehensive code quality improvements to our Python SDKs. Generated SDKs now produce Ruff-compatible code that adheres to PEP 8 and PEP 257 style guidelines.

Key outcomes:

  • Cleaner, more maintainable SDK code that follows modern Python best practices, with properly formatted docstrings, organized imports, and consistent styling
  • CI/CD integration ready with included ruff.toml configuration for automated linting

The improvements span string literal consistency, import organization, docstring formatting, line length management, and formatter-friendly structure. Where linting rules could potentially impact existing consumer code, they are intentionally bypassed to preserve behavior.

Zero-Downtime Upgrade

  • No action required. These improvements maintain full backward compatibility with existing SDK implementations. No breaking changes are included.
  • Simply regenerate your Python SDKs to take advantage of these enhancements

Quick Reference

ImprovementWhat ChangedWhy It Matters
Line Length & Formatting StandardsConsistent line wrapping with trailing commas in multi-line constructsCleaner git diffs and formatter compatibility
Docstring StandardizationAll docstrings now follow PEP 257 with imperative mood and complete Args/Returns sectionsBetter IDE autocomplete and auto-generated documentation
Import Organization & CleanupImports grouped by type (stdlib, third-party, local) and alphabetically sortedFaster module loading and clearer dependencies
String Literal StandardizationAll strings use double quotes throughoutEliminates escape sequences and improves readability
Whitespace NormalizationRemoved trailing whitespace and standardized file endingsCleaner version control and formatter compatibility
Code Quality & Variable ManagementRemoved unused variables, resolved naming conflicts, fixed mutable defaultsPrevents bugs and improves code safety
Return Statement OptimizationEliminated redundant else clauses and intermediate variablesSimpler control flow and reduced complexity
Python 3 ModernizationMigrated to f-strings and removed obsolete encoding declarationsImproved performance and cleaner syntax
Code Simplification & ReadabilityConverted complex ternary expressions to bool() and normalized comparisonsMore readable and Pythonic code
Module Export StandardsAlphabetically sorted __all__ exportsPredictable and maintainable public APIs
Code Maintenance & Best PracticesRemoved redundant pass, clarified boolean expressions, added missing __init__.pyBetter maintainability and fewer edge cases
Linting with RuffIncluded ruff.toml configuration in every generated SDKReady for CI/CD linting enforcement

Details

Line Length & Formatting Standards

Applied line wrapping to maintain a unified line length and introduced trailing commas in multi-line constructs where applicable. These formatting standards facilitate cleaner version control diffs and improve compatibility with automatic code formatters.

# Extract variables from the dictionary
frame_ctrl =\
dictionary.get("frame_ctrl")\
if dictionary.get("frame_ctrl")\
else APIHelper.SKIP
payload =\
dictionary.get("payload")\
if dictionary.get("payload")\
else APIHelper.SKIP

Docstring Standardization

Comprehensively refactored docstrings to achieve full PEP 257 and pydocstyle compliance. Key improvements include: imperative mood usage in summary lines, proper blank line placement, complete documentation coverage for all public modules/classes/methods, and correct positioning and spacing of triple-quote delimiters and section separators.

def bundledetails(self,
apikey,
request_id,
body=None):
"""Perform a POST request to
/fleetmanagement/v1/restriction/bundledetails.

This API allows to get the details of a specific card bundle. It returns the
bundle basic details along with the cards in the bundle and restrictions
applied on them.

Returns:
BundleDetailsResponse: Response from the API. OK

"""

@classmethod
def from_dictionary(cls,
dictionary):
"""Create an instance of this model from a dictionary

Args:
dictionary (dictionary): A dictionary representation of the object
as obtained from the deserialization of the server's response. The
keys MUST match property names in the API description.

Returns:
object: An instance of this structure class.

"""

def __repr__(self):
"""Return an unambiguous string representation."""
return...

Import Organization & Cleanup

Reorganized imports according to standard Python conventions with proper grouping (standard library, third-party packages, local modules) and alphabetical sorting within each group. Eliminated all unused import statements across the codebase. These changes reduce module loading overhead and improve dependency transparency.

from apimatic_core.utilities.comparison_helper import (
ComparisonHelper,
)

from mistapi.api_helper import APIHelper
from mistapi.models.utils_clear_macs import (
UtilsClearMacs,
)

String Literal Standardization

Implemented consistent double-quote formatting for all string literals throughout the SDK codebase, eliminating unnecessary escape sequences within quoted strings.

"last_status": "last_status",
"linked_by": "linked_by",
"max_daily_api_requests": "max_daily_api_requests",

Whitespace Normalization

Eliminated trailing whitespace characters, sanitized blank lines containing only whitespace, and standardized file termination with a single newline character. These corrections minimize version control noise and ensure compatibility with automated code formatters.

    def test_get_date(self):
"""
Api call test for `test_get_date`.
"""
# Perform the API call through the SDK function
result = self.controller.get_date()
# Test response code
assert self.response_catcher.response.text ==\
"5147483647"
# Test whether the captured response is as we expected
assert result is not None
assert self.response_catcher.response.text ==\
"1994-02-13"

Code Quality & Variable Management

  • Eliminated unused variable assignments and redundant f-string literals without interpolation placeholders.
  • Resolved naming conflicts including shadowed imports and redefined variables, and removed unused parameters from static methods.
  • Refactored default argument patterns to prevent mutable default issues by replacing function calls with constant values or None, with initialization logic moved into the function body.
@staticmethod
def _make_request(body_obj) -> Request:
"""
Create a webhook HTTP request with the given payload.

:param body_obj: The body object to serialize as JSON.
"""
raw = TestWebhooks1Handler._json_bytes(body_obj)

url="https://example.test/callbacks",
headers={
"Content-Type": "application/json",
},

Return Statement Optimization

Simplified control flow by eliminating redundant else clauses after return statements and removing superfluous variable assignments immediately preceding return operations. These refinements enhance code readability and reduce unnecessary complexity.

@staticmethod
def _make_request(body_obj) -> Request:
raw = TestWebhooks1Handler._json_bytes(body_obj)
return Request(
method="POST",
raw_body=raw,
)

@staticmethod
def _compute_signature(
secret_key: str,
) -> str:
signature_value_template = "{digest}"
if "{digest}" in signature_value_template:
return signature_value_template.replace("{digest}", secret_key)
return signature_value_template

Python 3 Modernization

Removed obsolete UTF-8 encoding declarations (# -*- coding: utf-8 -*-), which are unnecessary in Python 3, and migrated from str.format() method calls to f-string literals for improved readability and runtime performance.

class BearerAuth(HeaderAuth):
def __init__(self, auth_credentials_model):
auth_params = {}
if self._access_token:
auth_params = {"Authorization": f"Bearer {self._access_token}"}
super().__init__(auth_params=auth_params)

Code Simplification & Readability

Refactored ternary expressions of the form True if condition else False to use the more concise bool(condition) construct, and normalized comparison ordering by converting Yoda conditions (literal-first comparisons) to conventional variable-first syntax.

    def test_get_date(self):
"""
Api call test for `test_get_date`.
"""
# Perform the API call through the SDK function
result = self.controller.get_date()
# Test response code
assert self.response_catcher.response.text ==\
"5147483647"
# Test whether the captured response is as we expected
assert result is not None
assert self.response_catcher.response.text ==\
"1994-02-13"

Module Export Standards

Removed redundant TODO comments and implemented alphabetical sorting of __all__ module exports to ensure predictable and maintainable public API definitions.

__all__ = [
"api_controller",
"base_controller",
]

Code Maintenance & Best Practices

  • Eliminated redundant pass statements that serve no functional purpose.
  • Replaced typographically ambiguous Unicode quotation marks (RIGHT SINGLE QUOTATION MARK: ' ) with standard ASCII single quotes for consistency.
  • Added explicit parentheses to complex boolean expressions mixing and/or operators to clarify operator precedence and prevent logical errors.
  • Introduced missing __init__.py files in implicit namespace packages to establish explicit package boundaries where appropriate.
class Foo:
@classmethod
def setUpClass(cls):
assert (
isinstance(event, str) or
isinstance(event, int) or
(isinstance(event, list) and all(isinstance(x, str) for x in event)) or
(isinstance(event, list) and all(isinstance(x, int) for x in event))
)


Linting with Ruff

Each generated SDK now includes a ruff.toml configuration file that codifies these quality standards. You can integrate Ruff linting into your development workflow:

ruff check . --config ruff.toml

Optionally apply auto-fixes and formatting:

ruff check . --fix --config ruff.toml

You can add this as a pipeline checkpoint (for example, fail the build if ruff check reports violations) to ensure ongoing adherence to the configured rules without impacting backward compatibility.