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.tomlconfiguration 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
| Improvement | What Changed | Why It Matters |
|---|---|---|
| Line Length & Formatting Standards | Consistent line wrapping with trailing commas in multi-line constructs | Cleaner git diffs and formatter compatibility |
| Docstring Standardization | All docstrings now follow PEP 257 with imperative mood and complete Args/Returns sections | Better IDE autocomplete and auto-generated documentation |
| Import Organization & Cleanup | Imports grouped by type (stdlib, third-party, local) and alphabetically sorted | Faster module loading and clearer dependencies |
| String Literal Standardization | All strings use double quotes throughout | Eliminates escape sequences and improves readability |
| Whitespace Normalization | Removed trailing whitespace and standardized file endings | Cleaner version control and formatter compatibility |
| Code Quality & Variable Management | Removed unused variables, resolved naming conflicts, fixed mutable defaults | Prevents bugs and improves code safety |
| Return Statement Optimization | Eliminated redundant else clauses and intermediate variables | Simpler control flow and reduced complexity |
| Python 3 Modernization | Migrated to f-strings and removed obsolete encoding declarations | Improved performance and cleaner syntax |
| Code Simplification & Readability | Converted complex ternary expressions to bool() and normalized comparisons | More readable and Pythonic code |
| Module Export Standards | Alphabetically sorted __all__ exports | Predictable and maintainable public APIs |
| Code Maintenance & Best Practices | Removed redundant pass, clarified boolean expressions, added missing __init__.py | Better maintainability and fewer edge cases |
| Linting with Ruff | Included ruff.toml configuration in every generated SDK | Ready 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.
- Before
- After
# 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
# 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.
- Before
- After
def bundledetails(self,
apikey,
request_id,
body=None):
"""Does a POST request to /fleetmanagement/v1/restriction/bundledetails.
This API allows you 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):
"""Creates an instance of this model from a dictionary
Returns:
object: An instance of this structure class.
"""
def __repr__(self):
return...
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.
- Before
- After
import json
from apimatic_core.utilities.comparison_helper import ComparisonHelper
from mistapi.api_helper import APIHelper
from mistapi.models.upgrade_bios_multi import UpgradeBiosMulti
from mistapi.models.utils_clear_bpdu import UtilsClearBpdu
from mistapi.models.utils_clear_macs import UtilsClearMacs
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.
- Before
- After
"last_status": 'last_status',
"linked_by": 'linked_by',
"max_daily_api_requests": 'max_daily_api_requests'
"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.
- Before
- After
def test_get_date(self):
# Perform the API call through the SDK function
result = self.controller.get_date()
# Test response code
assert '5147483647' == self.response_catcher.response.text
# Test whether the captured response is as we expected
assert result is not None
assert '1994-02-13' == self.response_catcher.response.text
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.
- Before
- After
@staticmethod
def _make_request(body_obj, add_signature_header = True) -> Request:
raw = TestWebhooks1Handler._json_bytes(body_obj)
url=f"https://example.test/callbacks",
headers={"Content-Type": "application/json"},
@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.
- Before
- After
@staticmethod
def _make_request(body_obj) -> Request:
raw = TestWebhooks1Handler._json_bytes(body_obj)
request = Request(
method="POST",
raw_body=raw,
)
return request
@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)
else:
return signature_value_template
@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.
- Before
- After
# -*- coding: utf-8 -*-
class BearerAuth(HeaderAuth):
def __init__(self, bearer_auth_credentials):
auth_params = {}
if self._access_token:
auth_params = {"Authorization": "Bearer {}".format(self._access_token)}
super().__init__(auth_params=auth_params)
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.
- Before
- After
def test_get_date(self):
# Perform the API call through the SDK function
result = self.controller.get_date()
# Test response code
assert '5147483647' == self.response_catcher.response.text
# Test whether the captured response is as we expected
assert result is not None
assert '1994-02-13' == self.response_catcher.response.text
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.
- Before
- After
# Todo: Add description for __all__
__all__ = [
'base_controller',
'api_controller',
]
__all__ = [
"api_controller",
"base_controller",
]
Code Maintenance & Best Practices
- Eliminated redundant
passstatements 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/oroperators to clarify operator precedence and prevent logical errors. - Introduced missing
__init__.pyfiles in implicit namespace packages to establish explicit package boundaries where appropriate.
- Before
- After
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)
# Use this method to submit a specific call recording for transcription. Depending on the length of the call and the number of other recordings in the queue, it may take different time for the transcription to be completed. Typically, the majority of calls are transcribed within 10 minutes. To receive an update once the transcription is completed, you can specify a webhook address in the `webhook_url` parameter to which the status update will be sent.
#
#
#The method returns an empty response with the “HTTP 200 OK” status code. Once the transcription is completed you’ll receive a POST callback to the provided webhook address:
#```
#{
# "uuid": "123",
# "status": "completed"
#}
#```
#
#* uuid - the unique identifier of the recorded call
#* status - status of the operation. Can be either `completed` meaning the recorded call was successfully transcribed or `failed` which means that there was an error while transcribing the call.
pass
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.