python Rules

13 rules found for python

HTTP conventions in API endpoints

Ensure that for any new endpoint, the status code is matched with the correct purpose: - Use 401 Unauthorized for authentication failures (when credentials are missing or invalid) - Use 403 Forbidden for authorization failures (when user is authenticated but lacks required permissions) - Use 404 Not Found for resources that don't exist - Use 400 Bad Request for invalid request parameters - Use 500 Internal Server Error for server-side errors Bad: `python Wrong status code for permission error @app.route('/resource') def get_resource(): if not user.is_authenticated: return jsonify({"error": "Permission denied"}), 401 if not user.has_permission('read_resource'): return jsonify({"error": "Permission denied"}), 401 # Wrong code # ... ` Good: `python Correct status codes for different scenarios @app.route('/resource') def get_resource(): if not user.is_authenticated: return jsonify({"error": "Authentication required"}), 401 if not user.has_permission('read_resource'): return jsonify({"error": "Permission denied"}), 403 # Correct code # ... `

python

flask

quart

Avoid duplicate words in Python

Check all text elements (comments, docstrings, and string literals) for duplicate adjacent words for typos or duplicates. Bad: `python This function validates the the input parameters def validate_input(data): ... ` Good: `python This function validates the input parameters def validate_input(data): ... `

python

Self documenting code in Python

Avoid unnecessary explanatory comments for code that is self-documenting. Comments should only be used when they add context that the code itself cannot convey. Bad: `python Join the test directory with the base directory test_dir = os.path.join(BASE_DIR, test_case.identifier) ` Good: `python test_dir = os.path.join(BASE_DIR, test_case.identifier) `

python

Avoid print in Python tests

Avoid using print() statements in test files. Bad: `python def test_example(): result = some_function() print(result) # Debugging statement left in the code assert result == expected_value ` Good: `python def test_example(): result = some_function() assert result == expected_value `

python

Consistent error classes in Python

Use consistent naming conventions for error classes in Python. Bad: `python class PublicAPiError(Exception): # Inconsistent casing in "APi" - should be either "Api" or "API" pass class UnauthorizedHTtpError(Exception): # Inconsistent casing in "HTtp" - should be either "Http" or "HTTP" pass ` Good: `python class PublicApiError(Exception): # Consistent Pascal casing with "Api" pass class UnauthorizedHttpError(Exception): # Consistent Pascal casing with "Http" pass `

python

Python DRY

Avoid duplicating code in Python. Extract repeated logic into reusable functions, classes, or constants. You may have to search the codebase to see if the function or class is already defined. Bad: `python Duplicated class definitions class User: def __init__(self, id: str, name: str): self.id = id self.name = name class UserProfile: def __init__(self, id: str, name: str): self.id = id self.name = name Magic numbers repeated page_size = 10 items_per_page = 10 ` Good: `python Reusable class and constant class User: def __init__(self, id: str, name: str): self.id = id self.name = name PAGE_SIZE = 10 `

python

Avoid duplicate variable reassignment in Python

Avoid assigning a variable to itself or reassigning a variable with the same value. Bad: `python Redundant self-assignment x = 10 x = x # Unnecessary reassignment Duplicate assignment with the same value y = "hello" ... some code ... y = "hello" # Unnecessary reassignment with identical value ` Good: `python Single, clear assignment x = 10 Only reassign when the value changes y = "hello" ... some code ... y = "updated value" # Value actually changes `

python

Early returns in Python

Use early returns to reduce nesting levels. Instead of wrapping large code blocks in conditional statements, return early when conditions are not met. Bad: `python def process_user(user): if user is not None: if user.is_active: # Many lines of processing code result = perform_complex_operation(user) return result return None ` Good: `python def process_user(user): if user is None: return None if not user.is_active: return None # Now we can work with user without nesting # Many lines of processing code result = perform_complex_operation(user) return result `

python

No generic except in Python

Avoid using generic except: or except Exception: statements. Bad: `python def read_config_file(filepath): try: with open(filepath, 'r') as f: return json.load(f) except Exception: logger.error("Something went wrong") return {} ` `python def read_config_file(filepath): try: with open(filepath, 'r') as f: return json.load(f) except: return {} `

python

No inline imports in Python

Place all import statements at the top of the file. Bad: `python def process_data(data: Dict) -> List: import os # Inline import import json # Inline import from mymodule import MyClass # Inline import file_path = os.path.join("data", "output.json") with open(file_path, "w") as f: json.dump(data, f) processor = MyClass() return processor.transform(data) ` Good: `python import os import json from typing import Dict, List from mymodule import MyClass def process_data(data: Dict) -> List: # Use imported modules here file_path = os.path.join("data", "output.json") with open(file_path, "w") as f: json.dump(data, f) processor = MyClass() return processor.transform(data) `

python

No unused code in python

Do not leave commented-out code blocks in Python files. If code is no longer needed, remove it entirely rather than commenting it out. Bad: `python def calculate_total(items): total = 0 for item in items: total += item.price # Old calculation method that we might need later # subtotal = 0 # for item in items: # if item.type != 'tax': # subtotal += item.price # tax = calculate_tax(subtotal) # total = subtotal + tax return total ` Good: `python def calculate_total(items): total = 0 for item in items: total += item.price return total `

python

Unnecessary else blocks in Python

Avoid unnecessary else blocks when the if block ends with a return statement, break, continue, or similar control flow statements. Bad: `python def process_value(value): if value > 10: return "high" else: return "low" ` `python def check_items(items): for item in items: if len(item) > 5: print("Long item:", item) continue else: print("Short item:", item) ` Good: `python def process_value(value): if value > 10: return "high" return "low" ` `python def check_items(items): for item in items: if len(item) > 5: print("Long item:", item) continue print("Short item:", item) `

python

Avoid unncecessary try except in Python

When using try-except blocks in Python, keep the try block focused only on the code that can raise the expected exception. Bad: `python try: # Large block of code with many potential errors user_data = get_user_data() process_data(user_data) save_to_db(user_data) except (NetworkError, DBError): logger.error("Operation failed") ` Bad: `python try: # Contains only one potential error but still # has a block of code unrelated to the exception url = "https://google.com" url += "/?search=hello" response = requests.get(url) data = response.json() print(data) except NetworkError as e: logger.error(f"Error: {e}") ` Bad: `python Try except blocks are nested into each other try: response = client.beta.chat.completions.parse( model="some-model", messages=[ {"role": "system", "content": "hello"}, {"role": "user", "content": "how are you"}, ], ) try: json.loads(response.choices[0].message.parsed) except json.JSONDecodeError as e: logger.error(f"Decode failed: {e}") except requests.RequestException as e: logger.error(f"Error: {e}") ` Good: `python try: # Only one function that could have an error user_data = get_user_data() except NetworkError: logger.error("Failed to fetch user data") return Cannot raise an exception so it doesn't need to be handled process_data(user_data) try: # Only one potential error save_to_db(user_data) except DBError: logger.error("Failed to save to database") return ` Good: `python url = "https://google.com" url += "/?search=hello" Network call is a separate try except block try: response = requests.get(url) response.raise_for_status() except RequestException as e: logger.error(f"Error: {e}") Getting response in json is a separate try except block try: data = response.json() except JSONDecodeError as e: logger.error(f"Error: {e}") ` Good: `python Blocks that were nested before are now unnested into separate blocks try: response = client.beta.chat.completions.parse( model="some-model", messages=[ {"role": "system", "content": "hello"}, {"role": "user", "content": "how are you"}, ], ) except requests.RequestException as e: logger.error(f"Error: {e}") try: json.loads(response.choices[0].message.parsed) except json.JSONDecodeError as e: logger.error(f"Decode failed: {e}") `

python