
Python Style Guide
- 2 installs
- 404 repo stars
- Updated August 5, 2026
- aiskillstore/marketplace
python-style-guide is a skill that applies Google's Python Style Guide conventions when writing or reviewing Python code.
About
This skill provides Python coding guidelines based on Google's Python Style Guide. It covers language rules like imports, exceptions and type annotations, plus style rules for naming, formatting, and docstrings. A developer uses it when writing new Python code or reviewing existing code for style consistency.
- Python style rules based on Google's Python Style Guide
- Imports, exceptions, type annotations, naming conventions
- Google-style docstring format and formatting rules
Python Style Guide by the numbers
- 2 all-time installs (skills.sh)
- Ranked #236 of 290 Python skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
python-style-guide capabilities & compatibility
- Capabilities
- code review · refactoring
- Use cases
- code review · refactoring · documentation
- Pricing
- Free
What python-style-guide says it does
Comprehensive guidelines for writing clean, maintainable Python code based on [Google's Python Style Guide](https://google.github.io/styleguide/pyguide.html).
Use `import` statements for packages and modules only, not for individual classes or functions.
npx skills add https://github.com/aiskillstore/marketplace --skill python-style-guideAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 404 |
| Last updated | August 5, 2026 |
| Repository | aiskillstore/marketplace ↗ |
What it does
Apply Google-style Python conventions when writing or reviewing Python code for style consistency.
Who is it for?
Developers who want consistent, Google-style Python formatting and conventions.
Skip if: Non-Python languages or automated linting configuration.
When should I use this skill?
Writing Python code, reviewing it for style, or refactoring for consistency.
What you get
Produces Python code that follows Google's style rules for imports, exceptions, typing, and docstrings.
- style-consistent Python code
- Google-style docstrings
By the numbers
- 6-row naming-convention table
- 80-character maximum line length
- 4-space indentation rule
Files
Python Style Guide
Comprehensive guidelines for writing clean, maintainable Python code based on Google's Python Style Guide.
Core Philosophy
BE CONSISTENT. Match the style of the code around you. Use these guidelines as defaults, but always prioritize consistency with existing code.
Language Rules
Imports
Use import statements for packages and modules only, not for individual classes or functions.
Yes:
from doctor.who import jodie
import sound_effects.utilsNo:
from sound_effects.utils import EffectsRegistry # Don't import classes directlyImport Formatting
- Group imports: standard library, third-party, application-specific
- Alphabetize within each group
- Use absolute imports (not relative imports)
- One import per line (except for multiple items from
typingorcollections.abc)
# Standard library
import os
import sys
# Third-party
import numpy as np
import tensorflow as tf
# Application-specific
from myproject.backend import api_utilsExceptions
Use exceptions appropriately. Do not suppress errors with bare except: clauses.
Yes:
try:
result = risky_operation()
except ValueError as e:
logging.error(f"Invalid value: {e}")
raiseNo:
try:
result = risky_operation()
except: # Too broad, hides bugs
passType Annotations
Annotate all function signatures. Type annotations improve code readability and catch errors early.
General rules:
- Annotate all public APIs
- Use built-in types (
list,dict,set) instead oftyping.List, etc. (Python 3.9+) - Import typing symbols directly:
from typing import Any, Union - Use
Noneinstead oftype(None)orNoneType
def fetch_data(url: str, timeout: int = 30) -> dict[str, Any]:
"""Fetch data from URL."""
...
def process_items(items: list[str]) -> None:
"""Process a list of items."""
...Default Argument Values
Never use mutable objects as default values in function definitions.
Yes:
def foo(a: int, b: list[int] | None = None) -> None:
if b is None:
b = []No:
def foo(a: int, b: list[int] = []) -> None: # Mutable default - WRONG!
b.append(a)True/False Evaluations
Use implicit false where possible. Empty sequences, None, and 0 are false in boolean contexts.
Yes:
if not users: # Preferred
if not some_dict:
if value:No:
if len(users) == 0: # Verbose
if users == []:
if value == True: # Never compare to True/False explicitlyComprehensions & Generators
Use comprehensions and generators for simple cases. Keep them readable.
Yes:
result = [x for x in data if x > 0]
squares = (x**2 for x in range(10))No:
# Too complex
result = [
x.strip().lower() for x in data
if x and len(x) > 5 and not x.startswith('#')
for y in x.split(',') if y
] # Use a regular loop insteadLambda Functions
Use lambdas for one-liners only. For anything complex, define a proper function.
Yes:
sorted(data, key=lambda x: x.timestamp)Acceptable but prefer named function:
def get_timestamp(item):
return item.timestamp
sorted(data, key=get_timestamp)Style Rules
Line Length
Maximum line length: 80 characters. Exceptions allowed for imports, URLs, and long strings that can't be broken.
Indentation
Use 4 spaces per indentation level. Never use tabs.
For hanging indents, align wrapped elements vertically or use 4-space hanging indent:
# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Hanging indent (4 spaces)
foo = long_function_name(
var_one, var_two, var_three,
var_four)Blank Lines
- Two blank lines between top-level definitions
- One blank line between method definitions
- Use blank lines sparingly within functions to show logical sections
Naming Conventions
| Type | Convention | Examples |
|---|---|---|
| Packages/Modules | lower_with_under | my_module.py |
| Classes | CapWords | MyClass |
| Functions/Methods | lower_with_under() | my_function() |
| Constants | CAPS_WITH_UNDER | MAX_SIZE |
| Variables | lower_with_under | my_var |
| Private | _leading_underscore | _private_var |
Avoid:
- Single character names except for counters/iterators (
i,j,k) - Dashes in any name
__double_leading_and_trailing_underscore__(reserved for Python)
Comments and Docstrings
Docstring Format
Use Google-style docstrings for all public modules, functions, classes, and methods.
Function docstring:
def fetch_smalltable_rows(
table_handle: smalltable.Table,
keys: Sequence[bytes | str],
require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
"""Fetches rows from a Smalltable.
Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.
Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: If True, raise ValueError if any key is missing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings.
Raises:
IOError: An error occurred accessing the smalltable.
ValueError: A key is missing and require_all_keys is True.
"""
...Class docstring:
class SampleClass:
"""Summary of class here.
Longer class information...
Longer class information...
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam: bool = False):
"""Initializes the instance based on spam preference.
Args:
likes_spam: Defines if instance exhibits this preference.
"""
self.likes_spam = likes_spam
self.eggs = 0Block and Inline Comments
- Use complete sentences with proper capitalization
- Block comments indent to the same level as the code
- Inline comments should be separated by at least 2 spaces
- Use inline comments sparingly
# Block comment explaining the following code.
# Can span multiple lines.
x = x + 1 # Inline comment (use sparingly)Strings
Use f-strings for formatting (Python 3.6+).
Yes:
x = f"name: {name}; score: {score}"Acceptable:
x = "name: %s; score: %d" % (name, score)
x = "name: {}; score: {}".format(name, score)No:
x = "name: " + name + "; score: " + str(score) # Avoid + for formattingLogging
Use % formatting for logging, not f-strings (allows lazy evaluation):
logging.info("Request from %s resulted in %d", ip_address, status_code)Files and Resources
Always use context managers (with statements) for file operations:
with open("file.txt") as f:
data = f.read()Statements
Generally avoid multiple statements on one line.
Yes:
if foo:
bar()No:
if foo: bar() # AvoidMain
For executable scripts, use:
def main():
...
if __name__ == "__main__":
main()Function Length
Keep functions focused and reasonably sized. If a function exceeds about 40 lines, consider splitting it unless it remains very readable.
Type Annotation Details
Forward Declarations
Use string quotes for forward references:
class MyClass:
def method(self) -> "MyClass":
return selfType Aliases
Create aliases for complex types:
from typing import TypeAlias
ConnectionOptions: TypeAlias = dict[str, str]
Address: TypeAlias = tuple[str, int]
Server: TypeAlias = tuple[Address, ConnectionOptions]TypeVars
Use descriptive names for TypeVars:
from typing import TypeVar
_T = TypeVar("_T") # Good: private, unconstrained
AddableType = TypeVar("AddableType", int, float, str) # Good: descriptiveGenerics
Always specify type parameters for generic types:
Yes:
def get_names(employee_ids: list[int]) -> dict[int, str]:
...No:
def get_names(employee_ids: list) -> dict: # Missing type parameters
...Imports for Typing
Import typing symbols directly:
from collections.abc import Mapping, Sequence
from typing import Any, Union
# Use built-in types for containers (Python 3.9+)
def foo(items: list[str]) -> dict[str, int]:
...Common Patterns
Properties
Use properties for simple attribute access:
class Square:
def __init__(self, side: float):
self._side = side
@property
def area(self) -> float:
return self._side ** 2Conditional Expressions
Use ternary operators for simple conditions:
x = "yes" if condition else "no"Context Managers
Create custom context managers when appropriate:
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwargs):
resource = acquire_resource(*args, **kwargs)
try:
yield resource
finally:
release_resource(resource)Linting
Run pylint on all Python code. Suppress warnings only when necessary with clear explanations:
dict = 'something' # pylint: disable=redefined-builtinSummary
When writing Python code:
1. Use type annotations for all functions 2. Follow naming conventions consistently 3. Write clear docstrings for all public APIs 4. Keep functions focused and reasonably sized 5. Use comprehensions for simple cases 6. Prefer implicit false in boolean contexts 7. Use f-strings for formatting 8. Always use context managers for resources 9. Run pylint and fix issues 10. BE CONSISTENT with existing code
Additional Resources
For detailed reference on specific topics, see:
- references/advanced_types.md - Advanced type annotation patterns including Protocol, TypedDict, Literal, ParamSpec, and more
- references/antipatterns.md - Common Python mistakes and their fixes
- references/docstring_examples.md - Comprehensive docstring examples for all Python constructs
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
Advanced Type Annotations Reference
This document provides detailed guidance on advanced type annotation patterns in Python.
Union Types
Use | (union operator) for Python 3.10+ or Union for earlier versions:
# Python 3.10+
def process(value: int | str) -> None:
...
# Python 3.9 and earlier
from typing import Union
def process(value: Union[int, str]) -> None:
...Optional Types
Optional[X] is shorthand for X | None:
from typing import Optional
# These are equivalent:
def foo(x: Optional[int]) -> None: ...
def foo(x: int | None) -> None: ... # Preferred in Python 3.10+Callable Types
For function types, use Callable:
from collections.abc import Callable
def apply_func(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
# Callable[[arg1_type, arg2_type], return_type]For functions with variable arguments:
# Use ... for variable arguments
def accepts_any_callable(func: Callable[..., int]) -> None:
...Sequence, Mapping, and Iterable
Use abstract types from collections.abc when you don't need specific container features:
from collections.abc import Sequence, Mapping, Iterable
def process_items(items: Sequence[str]) -> None:
"""Works with lists, tuples, or any sequence."""
...
def process_mapping(data: Mapping[str, int]) -> None:
"""Works with dicts or any mapping."""
...
def sum_numbers(nums: Iterable[int]) -> int:
"""Works with any iterable."""
return sum(nums)Protocol and Structural Subtyping
Define structural types using Protocol:
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None:
...
def render(obj: Drawable) -> None:
obj.draw() # Any object with a draw() method worksTypedDict for Structured Dictionaries
Use TypedDict for dictionaries with known keys:
from typing import TypedDict
class Employee(TypedDict):
name: str
id: int
department: str
def process_employee(emp: Employee) -> None:
print(emp["name"]) # Type checker knows this key existsOptional fields:
from typing import TypedDict, NotRequired
class Employee(TypedDict):
name: str
id: int
department: NotRequired[str] # Optional fieldLiteral Types
Use Literal for specific values:
from typing import Literal
def set_mode(mode: Literal["read", "write", "append"]) -> None:
...
# Type checker ensures only these values are passed
set_mode("read") # OK
set_mode("delete") # ErrorGeneric Classes
Create generic classes with Generic:
from typing import Generic, TypeVar
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
# Usage
int_stack: Stack[int] = Stack()
int_stack.push(42)ParamSpec for Higher-Order Functions
Use ParamSpec to preserve function signatures:
from typing import ParamSpec, TypeVar, Callable
P = ParamSpec("P")
R = TypeVar("R")
def log_calls(func: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def greet(name: str, excited: bool = False) -> str:
return f"Hello, {name}{'!' if excited else '.'}"
# Type checker preserves the signature of greetTypeGuard for Type Narrowing
Use TypeGuard for custom type checking functions:
from typing import TypeGuard
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
def process(items: list[object]) -> None:
if is_str_list(items):
# Type checker knows items is list[str] here
print(", ".join(items))Annotating args and *kwargs
def foo(*args: int, **kwargs: str) -> None:
# args is tuple[int, ...]
# kwargs is dict[str, str]
...Overload for Multiple Signatures
Use @overload for functions with different return types based on arguments:
from typing import overload
@overload
def process(x: int) -> int: ...
@overload
def process(x: str) -> str: ...
def process(x: int | str) -> int | str:
if isinstance(x, int):
return x * 2
return x.upper()Self Type (Python 3.11+)
Use Self for methods that return the instance:
from typing import Self
class Builder:
def add_item(self, item: str) -> Self:
self.items.append(item)
return self # Return type is automatically the class type
def build(self) -> dict:
return {"items": self.items}For Python < 3.11, use TypeVar:
from typing import TypeVar
TBuilder = TypeVar("TBuilder", bound="Builder")
class Builder:
def add_item(self: TBuilder, item: str) -> TBuilder:
self.items.append(item)
return selfBest Practices
1. Use the most general type that works (e.g., Sequence over list) 2. Use Protocol for duck typing 3. Use TypedDict for structured dictionaries 4. Use Literal to restrict to specific values 5. Use TypeGuard for custom type narrowing 6. Always annotate public APIs 7. Use Any sparingly and explicitly when needed 8. Prefer built-in generic types (list, dict) over typing equivalents (Python 3.9+)
Python Anti-Patterns and Fixes
Common Python mistakes and their corrections.
1. Mutable Default Arguments
Anti-pattern:
def add_item(item, items=[]): # WRONG
items.append(item)
return itemsWhy it's wrong: The list is created once when the function is defined, not each time it's called.
Fix:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items2. Bare Except Clauses
Anti-pattern:
try:
risky_operation()
except: # WRONG - catches everything, including KeyboardInterrupt
handle_error()Fix:
try:
risky_operation()
except Exception as e: # Or specific exception types
logger.error(f"Operation failed: {e}")
handle_error()3. Using == for None Comparisons
Anti-pattern:
if value == None: # WRONG
...Fix:
if value is None:
...Why: is checks identity, == checks equality. None is a singleton.
4. Comparing Boolean Values Explicitly
Anti-pattern:
if flag == True: # WRONG
...
if len(items) > 0: # WRONG
...Fix:
if flag:
...
if items:
...5. Not Using Context Managers for Files
Anti-pattern:
f = open("file.txt") # WRONG - file may not close if error occurs
data = f.read()
f.close()Fix:
with open("file.txt") as f:
data = f.read()6. String Concatenation in Loops
Anti-pattern:
result = ""
for item in items:
result += str(item) # WRONG - creates new string each iterationFix:
result = "".join(str(item) for item in items)7. Modifying List While Iterating
Anti-pattern:
for item in items:
if should_remove(item):
items.remove(item) # WRONG - skips elementsFix:
items = [item for item in items if not should_remove(item)]
# Or
items[:] = [item for item in items if not should_remove(item)]8. Using eval() or exec()
Anti-pattern:
user_input = get_user_input()
result = eval(user_input) # WRONG - major security riskFix:
import ast
result = ast.literal_eval(user_input) # Only evaluates literals9. Not Using enumerate()
Anti-pattern:
i = 0
for item in items:
print(f"{i}: {item}")
i += 1Fix:
for i, item in enumerate(items):
print(f"{i}: {item}")10. Creating Empty Lists/Dicts Unnecessarily
Anti-pattern:
items = []
items.append(1)
items.append(2)
items.append(3)Fix:
items = [1, 2, 3]11. Not Using dict.get() with Defaults
Anti-pattern:
if key in my_dict:
value = my_dict[key]
else:
value = defaultFix:
value = my_dict.get(key, default)12. Using range(len()) Instead of enumerate()
Anti-pattern:
for i in range(len(items)):
item = items[i]
print(f"{i}: {item}")Fix:
for i, item in enumerate(items):
print(f"{i}: {item}")13. Not Using Collections Module
Anti-pattern:
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1Fix:
from collections import Counter
word_counts = Counter(words)14. Not Using defaultdict
Anti-pattern:
groups = {}
for item in items:
key = get_key(item)
if key not in groups:
groups[key] = []
groups[key].append(item)Fix:
from collections import defaultdict
groups = defaultdict(list)
for item in items:
key = get_key(item)
groups[key].append(item)15. Overly Complex Comprehensions
Anti-pattern:
result = [
transform(x)
for x in items
if condition1(x)
if condition2(x)
if condition3(x)
for y in x.sub_items
if condition4(y)
] # WRONG - too complexFix:
result = []
for x in items:
if condition1(x) and condition2(x) and condition3(x):
for y in x.sub_items:
if condition4(y):
result.append(transform(x))16. Not Using Path Objects
Anti-pattern:
import os
path = os.path.join(dir_name, "file.txt")
if os.path.exists(path):
with open(path) as f:
...Fix:
from pathlib import Path
path = Path(dir_name) / "file.txt"
if path.exists():
with path.open() as f:
...17. String Formatting with + or %
Anti-pattern:
message = "Hello, " + name + "! You have " + str(count) + " messages."
message = "Hello, %s! You have %d messages." % (name, count)Fix:
message = f"Hello, {name}! You have {count} messages."18. Not Using dataclasses
Anti-pattern:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.yFix:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float19. Lambda Abuse
Anti-pattern:
process = lambda x: x.strip().lower().replace(" ", "_")[:20] # WRONGFix:
def process(x: str) -> str:
"""Clean and truncate string."""
return x.strip().lower().replace(" ", "_")[:20]20. Not Using Sets for Membership Testing
Anti-pattern:
valid_codes = ["A1", "A2", "A3", ...] # Long list
if code in valid_codes: # O(n) lookup
...Fix:
valid_codes = {"A1", "A2", "A3", ...} # Set
if code in valid_codes: # O(1) lookup
...Summary
Key principles to avoid anti-patterns:
1. Use built-in functions and standard library when possible 2. Leverage context managers for resource management 3. Use appropriate data structures (sets for membership, Counter for counting) 4. Keep code readable and idiomatic 5. Use modern Python features (f-strings, dataclasses, Path) 6. Avoid premature optimization 7. Write explicit, clear code over clever code
Docstring Examples
Complete examples of Google-style docstrings for various Python constructs.
Module Docstring
"""This is an example module docstring.
This module provides utilities for processing user data. It includes functions
for validation, transformation, and persistence of user information.
Typical usage example:
user = create_user("John Doe", "john@example.com")
validate_user(user)
save_user(user)
"""Function Docstrings
Simple Function
def greet(name: str) -> str:
"""Returns a greeting message.
Args:
name: The name of the person to greet.
Returns:
A greeting string.
"""
return f"Hello, {name}!"Function with Multiple Arguments
def calculate_total(
price: float,
quantity: int,
discount: float = 0.0,
tax_rate: float = 0.0
) -> float:
"""Calculates the total cost including discount and tax.
Args:
price: The unit price of the item.
quantity: The number of items.
discount: The discount as a decimal (e.g., 0.1 for 10% off).
Defaults to 0.0.
tax_rate: The tax rate as a decimal (e.g., 0.08 for 8% tax).
Defaults to 0.0.
Returns:
The total cost after applying discount and tax.
Raises:
ValueError: If price or quantity is negative.
"""
if price < 0 or quantity < 0:
raise ValueError("Price and quantity must be non-negative")
subtotal = price * quantity * (1 - discount)
return subtotal * (1 + tax_rate)Function with Complex Return Type
def parse_config(
config_path: str
) -> tuple[dict[str, str], list[str]]:
"""Parses a configuration file.
Args:
config_path: Path to the configuration file.
Returns:
A tuple containing:
- A dictionary of configuration key-value pairs.
- A list of warning messages encountered during parsing.
Raises:
FileNotFoundError: If the config file doesn't exist.
ValueError: If the config file is malformed.
"""
...Function with Side Effects
def update_database(
user_id: int,
data: dict[str, Any]
) -> None:
"""Updates user data in the database.
Note:
This function modifies the database directly. Ensure proper
transaction handling in the calling code.
Args:
user_id: The ID of the user to update.
data: Dictionary containing fields to update.
Raises:
DatabaseError: If the database operation fails.
ValueError: If user_id is invalid or data is empty.
"""
...Class Docstrings
Simple Class
class User:
"""Represents a user in the system.
Attributes:
username: The user's unique username.
email: The user's email address.
created_at: Timestamp when the user was created.
"""
def __init__(self, username: str, email: str):
"""Initializes a new User.
Args:
username: The desired username.
email: The user's email address.
"""
self.username = username
self.email = email
self.created_at = datetime.now()Complex Class with Properties
class Rectangle:
"""Represents a rectangle with width and height.
This class provides methods for calculating area and perimeter,
and properties for accessing dimensions.
Attributes:
width: The width of the rectangle.
height: The height of the rectangle.
Example:
>>> rect = Rectangle(10, 5)
>>> rect.area
50
>>> rect.perimeter
30
"""
def __init__(self, width: float, height: float):
"""Initializes a Rectangle.
Args:
width: The width of the rectangle. Must be positive.
height: The height of the rectangle. Must be positive.
Raises:
ValueError: If width or height is not positive.
"""
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive")
self._width = width
self._height = height
@property
def width(self) -> float:
"""Gets the width of the rectangle."""
return self._width
@width.setter
def width(self, value: float) -> None:
"""Sets the width of the rectangle.
Args:
value: The new width. Must be positive.
Raises:
ValueError: If value is not positive.
"""
if value <= 0:
raise ValueError("Width must be positive")
self._width = value
@property
def area(self) -> float:
"""Calculates and returns the area of the rectangle."""
return self._width * self._height
@property
def perimeter(self) -> float:
"""Calculates and returns the perimeter of the rectangle."""
return 2 * (self._width + self._height)Generator Functions
def fibonacci(n: int) -> Iterator[int]:
"""Generates the first n Fibonacci numbers.
Args:
n: The number of Fibonacci numbers to generate.
Yields:
The next Fibonacci number in the sequence.
Raises:
ValueError: If n is negative.
Example:
>>> list(fibonacci(5))
[0, 1, 1, 2, 3]
"""
if n < 0:
raise ValueError("n must be non-negative")
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + bException Classes
class InvalidUserError(Exception):
"""Raised when user data is invalid.
This exception is raised during user validation when the provided
data doesn't meet the required criteria.
Attributes:
username: The invalid username that caused the error.
message: Explanation of the validation failure.
"""
def __init__(self, username: str, message: str):
"""Initializes the exception.
Args:
username: The username that failed validation.
message: Description of why validation failed.
"""
self.username = username
self.message = message
super().__init__(f"{username}: {message}")Context Manager
class DatabaseConnection:
"""Context manager for database connections.
Automatically handles connection setup and teardown.
Example:
>>> with DatabaseConnection("localhost", 5432) as conn:
... conn.execute("SELECT * FROM users")
"""
def __init__(self, host: str, port: int):
"""Initializes the database connection parameters.
Args:
host: The database host address.
port: The database port number.
"""
self.host = host
self.port = port
self._connection = None
def __enter__(self) -> "DatabaseConnection":
"""Establishes the database connection.
Returns:
The DatabaseConnection instance.
Raises:
ConnectionError: If connection cannot be established.
"""
self._connection = create_connection(self.host, self.port)
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
"""Closes the database connection.
Args:
exc_type: The exception type, if an exception occurred.
exc_val: The exception value, if an exception occurred.
exc_tb: The exception traceback, if an exception occurred.
Returns:
False to propagate exceptions, True to suppress them.
"""
if self._connection:
self._connection.close()
return FalseAsync Functions
async def fetch_data(url: str, timeout: float = 30.0) -> dict[str, Any]:
"""Asynchronously fetches data from a URL.
Args:
url: The URL to fetch data from.
timeout: Maximum time to wait for response in seconds.
Defaults to 30.0.
Returns:
A dictionary containing the fetched data.
Raises:
aiohttp.ClientError: If the request fails.
asyncio.TimeoutError: If the request times out.
Example:
>>> data = await fetch_data("https://api.example.com/data")
"""
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=timeout) as response:
return await response.json()Test Functions
def test_user_creation():
"""Tests that User objects are created correctly.
This test verifies:
- Username is set correctly
- Email is set correctly
- created_at is set to current time
"""
user = User("john_doe", "john@example.com")
assert user.username == "john_doe"
assert user.email == "john@example.com"
assert isinstance(user.created_at, datetime)Docstring Sections
Common sections in Google-style docstrings:
- Args: Function/method parameters
- Returns: Return value description
- Yields: For generator functions
- Raises: Exceptions that may be raised
- Attributes: For classes, describes instance attributes
- Example: Usage examples
- Note: Important notes or warnings
- Warning: Critical warnings
- Todo: Planned improvements
- See Also: Related functions or classes
Style Guidelines
1. Use triple double quotes (""") for all docstrings 2. First line is a brief summary (one sentence, no period needed if one line) 3. Leave a blank line before sections (Args, Returns, etc.) 4. Capitalize section headers 5. Use imperative mood ("Returns" not "Return") 6. Be specific and concise 7. Include type information in Args and Returns when not obvious from annotations 8. Always document exceptions that can be raised 9. Include examples for complex functions 10. Keep line length under 80 characters where possible
{
"schema_version": "2.0",
"meta": {
"generated_at": "2026-01-16T22:09:29.885Z",
"slug": "codingkaiser-python-style-guide",
"source_url": "https://github.com/CodingKaiser/claude-kaiser-skills/tree/main/python-style-guide",
"source_ref": "main",
"model": "claude",
"analysis_version": "3.0.0",
"source_type": "community",
"content_hash": "e114822b9413c285e73892df861b9da8c4b9faf8b91c943ba5a051295a39e604",
"tree_hash": "a39fc63f124d792ce342d67ddca1747cdde062b641d54170f3e5f919017db25f"
},
"skill": {
"name": "python-style-guide",
"description": "Comprehensive Python programming guidelines based on Google's Python Style Guide. Use when Claude needs to write Python code, review Python code for style issues, refactor Python code, or provide Python programming guidance. Covers language rules (imports, exceptions, type annotations), style rules (naming conventions, formatting, docstrings), and best practices for clean, maintainable Python code.",
"summary": "Comprehensive Python programming guidelines based on Google's Python Style Guide. Use when Claude ne...",
"icon": "🐍",
"version": "1.0.0",
"author": "CodingKaiser",
"license": "Complete terms in LICENSE.txt",
"category": "documentation",
"tags": [
"python",
"style-guide",
"best-practices",
"coding-standards",
"documentation"
],
"supported_tools": [
"claude",
"codex",
"claude-code"
],
"risk_factors": [
"external_commands",
"scripts",
"network"
]
},
"security_audit": {
"risk_level": "safe",
"is_blocked": false,
"safe_to_publish": true,
"summary": "This is a documentation-only skill containing markdown guidelines for Python code style. All 318 static findings are false positives: cryptographic alerts triggered by strings like 'A1'/'A2' in examples, backtick execution alerts from markdown code fences, and reconnaissance alerts from file operation examples. No executable code, network operations, or command execution.",
"risk_factor_evidence": [
{
"factor": "external_commands",
"evidence": [
{
"file": "references/advanced_types.md",
"line_start": 7,
"line_end": 7
},
{
"file": "references/advanced_types.md",
"line_start": 7,
"line_end": 7
},
{
"file": "references/advanced_types.md",
"line_start": 9,
"line_end": 18
},
{
"file": "references/advanced_types.md",
"line_start": 18,
"line_end": 22
},
{
"file": "references/advanced_types.md",
"line_start": 22,
"line_end": 22
},
{
"file": "references/advanced_types.md",
"line_start": 22,
"line_end": 24
},
{
"file": "references/advanced_types.md",
"line_start": 24,
"line_end": 30
},
{
"file": "references/advanced_types.md",
"line_start": 30,
"line_end": 34
},
{
"file": "references/advanced_types.md",
"line_start": 34,
"line_end": 36
},
{
"file": "references/advanced_types.md",
"line_start": 36,
"line_end": 43
},
{
"file": "references/advanced_types.md",
"line_start": 43,
"line_end": 47
},
{
"file": "references/advanced_types.md",
"line_start": 47,
"line_end": 51
},
{
"file": "references/advanced_types.md",
"line_start": 51,
"line_end": 55
},
{
"file": "references/advanced_types.md",
"line_start": 55,
"line_end": 57
},
{
"file": "references/advanced_types.md",
"line_start": 57,
"line_end": 71
},
{
"file": "references/advanced_types.md",
"line_start": 71,
"line_end": 75
},
{
"file": "references/advanced_types.md",
"line_start": 75,
"line_end": 77
},
{
"file": "references/advanced_types.md",
"line_start": 77,
"line_end": 86
},
{
"file": "references/advanced_types.md",
"line_start": 86,
"line_end": 90
},
{
"file": "references/advanced_types.md",
"line_start": 90,
"line_end": 92
},
{
"file": "references/advanced_types.md",
"line_start": 92,
"line_end": 102
},
{
"file": "references/advanced_types.md",
"line_start": 102,
"line_end": 106
},
{
"file": "references/advanced_types.md",
"line_start": 106,
"line_end": 113
},
{
"file": "references/advanced_types.md",
"line_start": 113,
"line_end": 117
},
{
"file": "references/advanced_types.md",
"line_start": 117,
"line_end": 119
},
{
"file": "references/advanced_types.md",
"line_start": 119,
"line_end": 128
},
{
"file": "references/advanced_types.md",
"line_start": 128,
"line_end": 132
},
{
"file": "references/advanced_types.md",
"line_start": 132,
"line_end": 134
},
{
"file": "references/advanced_types.md",
"line_start": 134,
"line_end": 152
},
{
"file": "references/advanced_types.md",
"line_start": 152,
"line_end": 156
},
{
"file": "references/advanced_types.md",
"line_start": 156,
"line_end": 158
},
{
"file": "references/advanced_types.md",
"line_start": 158,
"line_end": 175
},
{
"file": "references/advanced_types.md",
"line_start": 175,
"line_end": 179
},
{
"file": "references/advanced_types.md",
"line_start": 179,
"line_end": 181
},
{
"file": "references/advanced_types.md",
"line_start": 181,
"line_end": 191
},
{
"file": "references/advanced_types.md",
"line_start": 191,
"line_end": 195
},
{
"file": "references/advanced_types.md",
"line_start": 195,
"line_end": 200
},
{
"file": "references/advanced_types.md",
"line_start": 200,
"line_end": 204
},
{
"file": "references/advanced_types.md",
"line_start": 204,
"line_end": 206
},
{
"file": "references/advanced_types.md",
"line_start": 206,
"line_end": 219
},
{
"file": "references/advanced_types.md",
"line_start": 219,
"line_end": 223
},
{
"file": "references/advanced_types.md",
"line_start": 223,
"line_end": 225
},
{
"file": "references/advanced_types.md",
"line_start": 225,
"line_end": 235
},
{
"file": "references/advanced_types.md",
"line_start": 235,
"line_end": 239
},
{
"file": "references/advanced_types.md",
"line_start": 239,
"line_end": 248
},
{
"file": "references/advanced_types.md",
"line_start": 248,
"line_end": 252
},
{
"file": "references/advanced_types.md",
"line_start": 252,
"line_end": 252
},
{
"file": "references/advanced_types.md",
"line_start": 252,
"line_end": 253
},
{
"file": "references/advanced_types.md",
"line_start": 253,
"line_end": 254
},
{
"file": "references/advanced_types.md",
"line_start": 254,
"line_end": 255
},
{
"file": "references/advanced_types.md",
"line_start": 255,
"line_end": 256
},
{
"file": "references/advanced_types.md",
"line_start": 256,
"line_end": 258
},
{
"file": "references/advanced_types.md",
"line_start": 258,
"line_end": 259
},
{
"file": "references/advanced_types.md",
"line_start": 259,
"line_end": 259
},
{
"file": "references/advanced_types.md",
"line_start": 259,
"line_end": 259
},
{
"file": "references/antipatterns.md",
"line_start": 123,
"line_end": 123
},
{
"file": "references/antipatterns.md",
"line_start": 8,
"line_end": 12
},
{
"file": "references/antipatterns.md",
"line_start": 12,
"line_end": 17
},
{
"file": "references/antipatterns.md",
"line_start": 17,
"line_end": 23
},
{
"file": "references/antipatterns.md",
"line_start": 23,
"line_end": 28
},
{
"file": "references/antipatterns.md",
"line_start": 28,
"line_end": 33
},
{
"file": "references/antipatterns.md",
"line_start": 33,
"line_end": 36
},
{
"file": "references/antipatterns.md",
"line_start": 36,
"line_end": 42
},
{
"file": "references/antipatterns.md",
"line_start": 42,
"line_end": 47
},
{
"file": "references/antipatterns.md",
"line_start": 47,
"line_end": 50
},
{
"file": "references/antipatterns.md",
"line_start": 50,
"line_end": 53
},
{
"file": "references/antipatterns.md",
"line_start": 53,
"line_end": 56
},
{
"file": "references/antipatterns.md",
"line_start": 56,
"line_end": 58
},
{
"file": "references/antipatterns.md",
"line_start": 58,
"line_end": 58
},
{
"file": "references/antipatterns.md",
"line_start": 58,
"line_end": 58
},
{
"file": "references/antipatterns.md",
"line_start": 58,
"line_end": 63
},
{
"file": "references/antipatterns.md",
"line_start": 63,
"line_end": 68
},
{
"file": "references/antipatterns.md",
"line_start": 68,
"line_end": 71
},
{
"file": "references/antipatterns.md",
"line_start": 71,
"line_end": 76
},
{
"file": "references/antipatterns.md",
"line_start": 76,
"line_end": 81
},
{
"file": "references/antipatterns.md",
"line_start": 81,
"line_end": 85
},
{
"file": "references/antipatterns.md",
"line_start": 85,
"line_end": 88
},
{
"file": "references/antipatterns.md",
"line_start": 88,
"line_end": 91
},
{
"file": "references/antipatterns.md",
"line_start": 91,
"line_end": 96
},
{
"file": "references/antipatterns.md",
"line_start": 96,
"line_end": 100
},
{
"file": "references/antipatterns.md",
"line_start": 100,
"line_end": 103
},
{
"file": "references/antipatterns.md",
"line_start": 103,
"line_end": 105
},
{
"file": "references/antipatterns.md",
"line_start": 105,
"line_end": 110
},
{
"file": "references/antipatterns.md",
"line_start": 110,
"line_end": 114
},
{
"file": "references/antipatterns.md",
"line_start": 114,
"line_end": 117
},
{
"file": "references/antipatterns.md",
"line_start": 117,
"line_end": 121
},
{
"file": "references/antipatterns.md",
"line_start": 121,
"line_end": 126
},
{
"file": "references/antipatterns.md",
"line_start": 126,
"line_end": 129
},
{
"file": "references/antipatterns.md",
"line_start": 129,
"line_end": 132
},
{
"file": "references/antipatterns.md",
"line_start": 132,
"line_end": 135
},
{
"file": "references/antipatterns.md",
"line_start": 135,
"line_end": 140
},
{
"file": "references/antipatterns.md",
"line_start": 140,
"line_end": 145
},
{
"file": "references/antipatterns.md",
"line_start": 145,
"line_end": 148
},
{
"file": "references/antipatterns.md",
"line_start": 148,
"line_end": 151
},
{
"file": "references/antipatterns.md",
"line_start": 151,
"line_end": 156
},
{
"file": "references/antipatterns.md",
"line_start": 156,
"line_end": 161
},
{
"file": "references/antipatterns.md",
"line_start": 161,
"line_end": 164
},
{
"file": "references/antipatterns.md",
"line_start": 164,
"line_end": 166
},
{
"file": "references/antipatterns.md",
"line_start": 166,
"line_end": 171
},
{
"file": "references/antipatterns.md",
"line_start": 171,
"line_end": 176
},
{
"file": "references/antipatterns.md",
"line_start": 176,
"line_end": 179
},
{
"file": "references/antipatterns.md",
"line_start": 179,
"line_end": 181
},
{
"file": "references/antipatterns.md",
"line_start": 181,
"line_end": 186
},
{
"file": "references/antipatterns.md",
"line_start": 186,
"line_end": 190
},
{
"file": "references/antipatterns.md",
"line_start": 190,
"line_end": 193
},
{
"file": "references/antipatterns.md",
"line_start": 193,
"line_end": 196
},
{
"file": "references/antipatterns.md",
"line_start": 196,
"line_end": 201
},
{
"file": "references/antipatterns.md",
"line_start": 201,
"line_end": 208
},
{
"file": "references/antipatterns.md",
"line_start": 208,
"line_end": 211
},
{
"file": "references/antipatterns.md",
"line_start": 211,
"line_end": 214
},
{
"file": "references/antipatterns.md",
"line_start": 214,
"line_end": 219
},
{
"file": "references/antipatterns.md",
"line_start": 219,
"line_end": 226
},
{
"file": "references/antipatterns.md",
"line_start": 226,
"line_end": 229
},
{
"file": "references/antipatterns.md",
"line_start": 229,
"line_end": 235
},
{
"file": "references/antipatterns.md",
"line_start": 235,
"line_end": 240
},
{
"file": "references/antipatterns.md",
"line_start": 240,
"line_end": 250
},
{
"file": "references/antipatterns.md",
"line_start": 250,
"line_end": 253
},
{
"file": "references/antipatterns.md",
"line_start": 253,
"line_end": 260
},
{
"file": "references/antipatterns.md",
"line_start": 260,
"line_end": 265
},
{
"file": "references/antipatterns.md",
"line_start": 265,
"line_end": 271
},
{
"file": "references/antipatterns.md",
"line_start": 271,
"line_end": 274
},
{
"file": "references/antipatterns.md",
"line_start": 274,
"line_end": 280
},
{
"file": "references/antipatterns.md",
"line_start": 280,
"line_end": 285
},
{
"file": "references/antipatterns.md",
"line_start": 285,
"line_end": 288
},
{
"file": "references/antipatterns.md",
"line_start": 288,
"line_end": 291
},
{
"file": "references/antipatterns.md",
"line_start": 291,
"line_end": 293
},
{
"file": "references/antipatterns.md",
"line_start": 293,
"line_end": 298
},
{
"file": "references/antipatterns.md",
"line_start": 298,
"line_end": 309
},
{
"file": "references/antipatterns.md",
"line_start": 309,
"line_end": 312
},
{
"file": "references/antipatterns.md",
"line_start": 312,
"line_end": 319
},
{
"file": "references/antipatterns.md",
"line_start": 319,
"line_end": 324
},
{
"file": "references/antipatterns.md",
"line_start": 324,
"line_end": 326
},
{
"file": "references/antipatterns.md",
"line_start": 326,
"line_end": 329
},
{
"file": "references/antipatterns.md",
"line_start": 329,
"line_end": 333
},
{
"file": "references/antipatterns.md",
"line_start": 333,
"line_end": 338
},
{
"file": "references/antipatterns.md",
"line_start": 338,
"line_end": 342
},
{
"file": "references/antipatterns.md",
"line_start": 342,
"line_end": 345
},
{
"file": "references/antipatterns.md",
"line_start": 345,
"line_end": 349
},
{
"file": "references/docstring_examples.md",
"line_start": 7,
"line_end": 19
},
{
"file": "references/docstring_examples.md",
"line_start": 19,
"line_end": 25
},
{
"file": "references/docstring_examples.md",
"line_start": 25,
"line_end": 36
},
{
"file": "references/docstring_examples.md",
"line_start": 36,
"line_end": 40
},
{
"file": "references/docstring_examples.md",
"line_start": 40,
"line_end": 68
},
{
"file": "references/docstring_examples.md",
"line_start": 68,
"line_end": 72
},
{
"file": "references/docstring_examples.md",
"line_start": 72,
"line_end": 91
},
{
"file": "references/docstring_examples.md",
"line_start": 91,
"line_end": 95
},
{
"file": "references/docstring_examples.md",
"line_start": 95,
"line_end": 115
},
{
"file": "references/docstring_examples.md",
"line_start": 115,
"line_end": 121
},
{
"file": "references/docstring_examples.md",
"line_start": 121,
"line_end": 141
},
{
"file": "references/docstring_examples.md",
"line_start": 141,
"line_end": 145
},
{
"file": "references/docstring_examples.md",
"line_start": 145,
"line_end": 207
},
{
"file": "references/docstring_examples.md",
"line_start": 207,
"line_end": 211
},
{
"file": "references/docstring_examples.md",
"line_start": 211,
"line_end": 235
},
{
"file": "references/docstring_examples.md",
"line_start": 235,
"line_end": 239
},
{
"file": "references/docstring_examples.md",
"line_start": 239,
"line_end": 261
},
{
"file": "references/docstring_examples.md",
"line_start": 261,
"line_end": 265
},
{
"file": "references/docstring_examples.md",
"line_start": 265,
"line_end": 313
},
{
"file": "references/docstring_examples.md",
"line_start": 313,
"line_end": 317
},
{
"file": "references/docstring_examples.md",
"line_start": 317,
"line_end": 339
},
{
"file": "references/docstring_examples.md",
"line_start": 339,
"line_end": 343
},
{
"file": "references/docstring_examples.md",
"line_start": 343,
"line_end": 356
},
{
"file": "references/docstring_examples.md",
"line_start": 356,
"line_end": 375
},
{
"file": "skill-report.json",
"line_start": 129,
"line_end": 141
},
{
"file": "SKILL.md",
"line_start": 19,
"line_end": 19
},
{
"file": "SKILL.md",
"line_start": 22,
"line_end": 25
},
{
"file": "SKILL.md",
"line_start": 25,
"line_end": 28
},
{
"file": "SKILL.md",
"line_start": 28,
"line_end": 30
},
{
"file": "SKILL.md",
"line_start": 30,
"line_end": 37
},
{
"file": "SKILL.md",
"line_start": 37,
"line_end": 37
},
{
"file": "SKILL.md",
"line_start": 37,
"line_end": 39
},
{
"file": "SKILL.md",
"line_start": 39,
"line_end": 50
},
{
"file": "SKILL.md",
"line_start": 50,
"line_end": 54
},
{
"file": "SKILL.md",
"line_start": 54,
"line_end": 57
},
{
"file": "SKILL.md",
"line_start": 57,
"line_end": 63
},
{
"file": "SKILL.md",
"line_start": 63,
"line_end": 66
},
{
"file": "SKILL.md",
"line_start": 66,
"line_end": 71
},
{
"file": "SKILL.md",
"line_start": 71,
"line_end": 79
},
{
"file": "SKILL.md",
"line_start": 79,
"line_end": 79
},
{
"file": "SKILL.md",
"line_start": 79,
"line_end": 79
},
{
"file": "SKILL.md",
"line_start": 79,
"line_end": 79
},
{
"file": "SKILL.md",
"line_start": 79,
"line_end": 80
},
{
"file": "SKILL.md",
"line_start": 80,
"line_end": 81
},
{
"file": "SKILL.md",
"line_start": 81,
"line_end": 81
},
{
"file": "SKILL.md",
"line_start": 81,
"line_end": 81
},
{
"file": "SKILL.md",
"line_start": 81,
"line_end": 83
},
{
"file": "SKILL.md",
"line_start": 83,
"line_end": 91
},
{
"file": "SKILL.md",
"line_start": 91,
"line_end": 98
},
{
"file": "SKILL.md",
"line_start": 98,
"line_end": 102
},
{
"file": "SKILL.md",
"line_start": 102,
"line_end": 105
},
{
"file": "SKILL.md",
"line_start": 105,
"line_end": 108
},
{
"file": "SKILL.md",
"line_start": 108,
"line_end": 112
},
{
"file": "SKILL.md",
"line_start": 112,
"line_end": 112
},
{
"file": "SKILL.md",
"line_start": 112,
"line_end": 115
},
{
"file": "SKILL.md",
"line_start": 115,
"line_end": 119
},
{
"file": "SKILL.md",
"line_start": 119,
"line_end": 122
},
{
"file": "SKILL.md",
"line_start": 122,
"line_end": 126
},
{
"file": "SKILL.md",
"line_start": 126,
"line_end": 133
},
{
"file": "SKILL.md",
"line_start": 133,
"line_end": 136
},
{
"file": "SKILL.md",
"line_start": 136,
"line_end": 139
},
{
"file": "SKILL.md",
"line_start": 139,
"line_end": 146
},
{
"file": "SKILL.md",
"line_start": 146,
"line_end": 153
},
{
"file": "SKILL.md",
"line_start": 153,
"line_end": 155
},
{
"file": "SKILL.md",
"line_start": 155,
"line_end": 158
},
{
"file": "SKILL.md",
"line_start": 158,
"line_end": 163
},
{
"file": "SKILL.md",
"line_start": 163,
"line_end": 177
},
{
"file": "SKILL.md",
"line_start": 177,
"line_end": 186
},
{
"file": "SKILL.md",
"line_start": 186,
"line_end": 198
},
{
"file": "SKILL.md",
"line_start": 198,
"line_end": 198
},
{
"file": "SKILL.md",
"line_start": 198,
"line_end": 199
},
{
"file": "SKILL.md",
"line_start": 199,
"line_end": 199
},
{
"file": "SKILL.md",
"line_start": 199,
"line_end": 200
},
{
"file": "SKILL.md",
"line_start": 200,
"line_end": 200
},
{
"file": "SKILL.md",
"line_start": 200,
"line_end": 201
},
{
"file": "SKILL.md",
"line_start": 201,
"line_end": 201
},
{
"file": "SKILL.md",
"line_start": 201,
"line_end": 202
},
{
"file": "SKILL.md",
"line_start": 202,
"line_end": 202
},
{
"file": "SKILL.md",
"line_start": 202,
"line_end": 203
},
{
"file": "SKILL.md",
"line_start": 203,
"line_end": 203
},
{
"file": "SKILL.md",
"line_start": 203,
"line_end": 206
},
{
"file": "SKILL.md",
"line_start": 206,
"line_end": 206
},
{
"file": "SKILL.md",
"line_start": 206,
"line_end": 206
},
{
"file": "SKILL.md",
"line_start": 206,
"line_end": 208
},
{
"file": "SKILL.md",
"line_start": 208,
"line_end": 217
},
{
"file": "SKILL.md",
"line_start": 217,
"line_end": 243
},
{
"file": "SKILL.md",
"line_start": 243,
"line_end": 246
},
{
"file": "SKILL.md",
"line_start": 246,
"line_end": 266
},
{
"file": "SKILL.md",
"line_start": 266,
"line_end": 275
},
{
"file": "SKILL.md",
"line_start": 275,
"line_end": 279
},
{
"file": "SKILL.md",
"line_start": 279,
"line_end": 286
},
{
"file": "SKILL.md",
"line_start": 286,
"line_end": 288
},
{
"file": "SKILL.md",
"line_start": 288,
"line_end": 291
},
{
"file": "SKILL.md",
"line_start": 291,
"line_end": 294
},
{
"file": "SKILL.md",
"line_start": 294,
"line_end": 297
},
{
"file": "SKILL.md",
"line_start": 297,
"line_end": 299
},
{
"file": "SKILL.md",
"line_start": 299,
"line_end": 303
},
{
"file": "SKILL.md",
"line_start": 303,
"line_end": 305
},
{
"file": "SKILL.md",
"line_start": 305,
"line_end": 307
},
{
"file": "SKILL.md",
"line_start": 307,
"line_end": 311
},
{
"file": "SKILL.md",
"line_start": 311,
"line_end": 313
},
{
"file": "SKILL.md",
"line_start": 313,
"line_end": 316
},
{
"file": "SKILL.md",
"line_start": 316,
"line_end": 323
},
{
"file": "SKILL.md",
"line_start": 323,
"line_end": 326
},
{
"file": "SKILL.md",
"line_start": 326,
"line_end": 329
},
{
"file": "SKILL.md",
"line_start": 329,
"line_end": 331
},
{
"file": "SKILL.md",
"line_start": 331,
"line_end": 337
},
{
"file": "SKILL.md",
"line_start": 337,
"line_end": 343
},
{
"file": "SKILL.md",
"line_start": 343,
"line_end": 355
},
{
"file": "SKILL.md",
"line_start": 355,
"line_end": 359
},
{
"file": "SKILL.md",
"line_start": 359,
"line_end": 365
},
{
"file": "SKILL.md",
"line_start": 365,
"line_end": 371
},
{
"file": "SKILL.md",
"line_start": 371,
"line_end": 377
},
{
"file": "SKILL.md",
"line_start": 377,
"line_end": 382
},
{
"file": "SKILL.md",
"line_start": 382,
"line_end": 389
},
{
"file": "SKILL.md",
"line_start": 389,
"line_end": 392
},
{
"file": "SKILL.md",
"line_start": 392,
"line_end": 395
},
{
"file": "SKILL.md",
"line_start": 395,
"line_end": 398
},
{
"file": "SKILL.md",
"line_start": 398,
"line_end": 404
},
{
"file": "SKILL.md",
"line_start": 404,
"line_end": 411
},
{
"file": "SKILL.md",
"line_start": 411,
"line_end": 419
},
{
"file": "SKILL.md",
"line_start": 419,
"line_end": 427
},
{
"file": "SKILL.md",
"line_start": 427,
"line_end": 433
},
{
"file": "SKILL.md",
"line_start": 433,
"line_end": 435
},
{
"file": "SKILL.md",
"line_start": 435,
"line_end": 441
},
{
"file": "SKILL.md",
"line_start": 441,
"line_end": 451
},
{
"file": "SKILL.md",
"line_start": 451,
"line_end": 455
},
{
"file": "SKILL.md",
"line_start": 455,
"line_end": 457
},
{
"file": "SKILL.md",
"line_start": 457,
"line_end": 459
}
]
},
{
"factor": "scripts",
"evidence": [
{
"file": "references/antipatterns.md",
"line_start": 123,
"line_end": 123
},
{
"file": "references/antipatterns.md",
"line_start": 128,
"line_end": 128
},
{
"file": "references/antipatterns.md",
"line_start": 123,
"line_end": 123
}
]
},
{
"factor": "network",
"evidence": [
{
"file": "references/docstring_examples.md",
"line_start": 334,
"line_end": 334
},
{
"file": "skill-report.json",
"line_start": 6,
"line_end": 6
},
{
"file": "SKILL.md",
"line_start": 9,
"line_end": 9
}
]
}
],
"critical_findings": [],
"high_findings": [],
"medium_findings": [],
"low_findings": [],
"dangerous_patterns": [],
"files_scanned": 6,
"total_lines": 2109,
"audit_model": "claude",
"audited_at": "2026-01-16T22:09:29.885Z"
},
"content": {
"user_title": "Apply Python Style Guidelines",
"value_statement": "This skill provides comprehensive Python programming guidelines following Google's Python Style Guide. It ensures code consistency, readability, and maintainability across Python projects.",
"seo_keywords": [
"python style guide",
"claude code",
"python coding standards",
"google style guide",
"claude",
"codex",
"python best practices",
"python linting",
"python docstrings",
"python type annotations"
],
"actual_capabilities": [
"Provides Python naming conventions for classes, functions, variables, and constants",
"Documents proper import organization and formatting standards",
"Explains type annotation best practices including Generics and Protocol",
"Shows correct exception handling and error management patterns",
"Details docstring formats using Google-style documentation"
],
"limitations": [
"Contains documentation only - does not execute or lint code",
"Does not provide automated code fixes or refactoring",
"Focuses on style rather than performance optimization",
"References Python 3.6+ features without version-specific alternatives"
],
"use_cases": [
{
"target_user": "Python developers",
"title": "Write consistent Python code",
"description": "Follow established naming, formatting, and documentation conventions for cleaner codebases."
},
{
"target_user": "Code reviewers",
"title": "Review Python submissions",
"description": "Use as a reference checklist when reviewing Python pull requests for style compliance."
},
{
"target_user": "Learning developers",
"title": "Learn Python best practices",
"description": "Study documented patterns to improve Python coding skills and write professional code."
}
],
"prompt_templates": [
{
"title": "Basic Python formatting",
"scenario": "Get style guidelines",
"prompt": "Write Python code following the style guide. Use 4 spaces for indentation and 80 character line limits."
},
{
"title": "Type annotations",
"scenario": "Add type hints",
"prompt": "Add type annotations to this Python function. Use Python 3.10 union syntax with | operator."
},
{
"title": "Docstring standards",
"scenario": "Document functions",
"prompt": "Write Google-style docstrings for these Python functions. Include Args, Returns, and Raises sections."
},
{
"title": "Review code style",
"scenario": "Check compliance",
"prompt": "Review this Python code against the style guide. Identify issues with imports, naming, and documentation."
}
],
"output_examples": [
{
"input": "Write a Python function to calculate factorial with proper type hints and docstring.",
"output": [
"Function uses type annotations: def factorial(n: int) -> int",
"Docstring follows Google style with Args and Returns sections",
"Code follows naming conventions for functions"
]
},
{
"input": "Review this Python class for style issues.",
"output": [
"Class naming follows CapWords convention",
"Methods use lower_with_under naming",
"Imports are grouped: stdlib, third-party, local"
]
},
{
"input": "Show how to handle exceptions properly in Python.",
"output": [
"Avoid bare except: clauses",
"Use specific exception types like ValueError",
"Re-raise exceptions when appropriate with raise"
]
}
],
"best_practices": [
"Use type annotations for all public function signatures to improve code clarity and enable static analysis",
"Organize imports in three groups: standard library, third-party, and application-specific modules",
"Write Google-style docstrings for all public modules, classes, and functions with Args, Returns, and Raises sections"
],
"anti_patterns": [
"Using mutable objects as default argument values (def foo(items=[]):) causes shared state bugs",
"Using bare except: clauses (except:) catches all exceptions including KeyboardInterrupt and hides bugs",
"Comparing to None using == instead of is (if x == None:) fails to use Python singleton semantics"
],
"faq": [
{
"question": "What Python version does this style guide target?",
"answer": "The guide references Python 3.6+ features like f-strings while noting alternatives for earlier versions."
},
{
"question": "Does this skill lint or format my code?",
"answer": "No. This skill provides guidelines and references. Use pylint or black for actual linting and formatting."
},
{
"question": "Are the rules mandatory or flexible?",
"answer": "Prioritize consistency with existing code. Use these guidelines as defaults when starting new projects."
},
{
"question": "What about import formatting?",
"answer": "Group imports by source type, alphabetize within groups, and use absolute imports for clarity."
},
{
"question": "Should I use typing module or built-in generics?",
"answer": "Prefer built-in generics (list, dict) over typing equivalents for Python 3.9+."
},
{
"question": "How strict is the 80 character line limit?",
"answer": "Use 80 characters as default. Allow exceptions for imports, URLs, and unbroken strings."
}
]
},
"file_structure": [
{
"name": "references",
"type": "dir",
"path": "references",
"children": [
{
"name": "advanced_types.md",
"type": "file",
"path": "references/advanced_types.md",
"lines": 260
},
{
"name": "antipatterns.md",
"type": "file",
"path": "references/antipatterns.md",
"lines": 362
},
{
"name": "docstring_examples.md",
"type": "file",
"path": "references/docstring_examples.md",
"lines": 385
}
]
},
{
"name": "LICENSE",
"type": "file",
"path": "LICENSE",
"lines": 396
},
{
"name": "SKILL.md",
"type": "file",
"path": "SKILL.md",
"lines": 483
}
]
}
Related skills
FAQ
What style is this based on?
Google's Python Style Guide.
What's the recommended line length?
Maximum 80 characters, with exceptions for imports, URLs, and unbreakable strings.