agentleFS
programmerrajaprogrammerraja/claude-code-toolbox/skills/Programming/python/SKILL.md

python

Skill1 starsChanged 5 days agoMITView on GitHub

If there can be many misses, sometimes dict.setdefault() or defaultdict is better.

54 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use android-kotlin, java and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • alinaqiSkill

    android-kotlin

    Android Kotlin development with Coroutines, Jetpack Compose, Hilt, and MockK testing

    Also in 4 projects that use this

  • testdino-hqSkill

    java

    Google's official Java style guide. Covers 2-space indentation, 100-char line limit, naming conventions, braces, imports, Javadoc, exception handling, lambdas, and streams. Enforces @Override annotations and specific imports.

    Also in 6 projects that use this

  • testdino-hqSkill

    cpp

    Google's official C++ style guide. Covers headers, naming conventions, formatting, classes, memory management, RAII, smart pointers, and modern C++ features.

    Also in 5 projects that use this

  • ffsshhttiikkSkill

    flutter

    Flutter cross-platform framework

    Also in 4 projects that use this

  • mcollinaSkill

    node

    Provides domain-specific best practices for Node.js development with TypeScript, covering type stripping, async patterns, error handling, streams, modules, testing, performance, caching, logging, and more. Use when setting up Node.js projects with native TypeScript support, configuring type stripping (--experimental-strip-types), writing Node 22+ TypeScript without a build step, or when the user mentions 'native TypeScript in Node', 'strip types', 'Node 22 TypeScript', '.ts files without compilation', 'ts-node alternative', or needs guidance on error handling, graceful shutdown, flaky tests, profiling, or environment configuration in Node.js. Helps configure tsconfig.json for type stripping, set up package.json scripts, handle module resolution and import extensions, and apply robust patterns across the full Node.js stack.

    Also in 4 projects that use this

  • VercelSkill

    react

    React renderer for json-render that turns JSON specs into React components. Use when working with @json-render/react, building React UIs from JSON, creating component catalogs, or rendering AI-generated specs.

    Also in 7 projects that use this

  • +1 more from testdino-hq

The file

Show its rules and text

We split this skill into the rules it gives an agent

78 rules. 0 are common, 50 are distinctive, and 28 are very specific to this project.

  • 0

    Common

    Most of the 47 edited versions we read keep these.

  • 50

    Distinctive

    This author's own choices. Worth a look.

  • 28

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use clear names and focused functions.

    line 4
  2. Distinctive:

    Follow PEP 8 and type hints where they improve maintenance.

    line 5
  3. Distinctive:

    Add tests before optimizing.

    line 6
  4. Very specific:

    Use cProfile, time, tracemalloc, or benchmark tools to find real bottlenecks.

    line 7
  5. Very specific:

    Membership testing: use set or frozenset, not repeatedly searching a list.

    line 11
  6. Very specific:

    Key/value lookup: use dict.

    line 12
  7. Very specific:

    Append and pop from the end: use list.

    line 13
  8. Very specific:

    Frequent insert/remove at both ends: use deque.

    line 14
  9. Very specific:

    Unique and order-independent values: use set.

    line 15
  10. Very specific:

    Immutable sequence: consider tuple.

    line 16
  11. Very specific:

    Large text built repeatedly: use "".join(parts), not repeated +=.

    line 17
  12. Very specific:

    Use functools.lru_cache or functools.cache only for genuinely cacheable pure functions.

    line 23
  13. Very specific:

    Avoid recalculating len(), attribute values or method calls in a tight loop.

    line 24
  14. Very specific:

    Prefer built-in functions such as sum(), any(), all(), min(), max(), sorted(), enumerate() and zip().

    line 38
  15. Distinctive:

    Use list, dict and set comprehensions for simple transformations.

    line 51
  16. Distinctive:

    Avoid deeply nested comprehensions.

    line 52
  17. Very specific:

    Use map() or filter() only if they are clearer or faster in context.

    line 53
  18. Very specific:

    Use break to stop early.

    line 61
  19. Distinctive:

    Avoid checking each item separately when vectorized or built-in operations exist.

    line 62
  20. Distinctive:

    Use a copy or a separate result collection when values change.

    line 64
  21. Very specific:

    Use with for files, locks, sockets and database connections.

    line 74
  22. Distinctive:

    Avoid creating temporary lists when a generator is sufficient.

    line 85
  23. Distinctive:

    Use slices carefully; slicing creates a new object.

    line 88
  24. Distinctive:

    Prefer tuple unpacking and generator expressions for short-lived values.

    line 89
  25. Distinctive:

    Put exception handling around only the potentially failing operation.

    line 99
  26. Very specific:

    If there can be many misses, sometimes dict.setdefault() or defaultdict is better.

    line 108
  27. Distinctive:

    Use f-strings for readable formatting.

    line 112
  28. Distinctive:

    Use prefix/suffix checks and membership efficiently.

    line 113
  29. Distinctive:

    Avoid parsing or splitting the same text repeatedly.

    line 114
  30. Very specific:

    Use bytes only when binary data is intentional.

    line 116
  31. Distinctive:

    Use connection pools for database or network resources.

    line 124
  32. Distinctive:

    Avoid holding large resources inside loops.

    line 125
  33. Distinctive:

    Use buffering for repeated file operations.

    line 126
  34. Distinctive:

    Do not perform network requests in nested loops unless necessary.

    line 127
  35. Distinctive:

    Use threading for I/O-bound tasks.

    line 130
  36. Distinctive:

    Use multiprocessing for CPU-bound parallel work.

    line 131
  37. Distinctive:

    Use async I/O for high-concurrency network or file tasks.

    line 133
  38. Distinctive:

    Prefer queues and messages over shared mutable objects.

    line 135
  39. Distinctive:

    Avoid global mutable state.

    line 139
  40. Very specific:

    Avoid excessive reflection or dynamic exec.

    line 140
  41. Very specific:

    Avoid repeated import calls inside loops.

    line 141
  42. Distinctive:

    Avoid shallow assumptions about object copy behavior.

    line 157
  43. Distinctive:

    Avoid long chains of attribute lookup when used repeatedly.

    line 158
  44. Distinctive:

    Remove large references when no longer needed.

    line 161
  45. Distinctive:

    Use generators for large sequences.

    line 162
  46. Distinctive:

    Use weak references for optional object tracking.

    line 164
  47. Very specific:

    Call gc.collect() manually only for specialized needs, not routinely.

    line 165
  48. Distinctive:

    Avoid creating large temporary objects in comprehensions.

    line 166
  49. Very specific:

    Use __slots__ only after measurement if many instances are created.

    line 167
  50. Distinctive:

    Keep classes focused and small.

    line 179
  51. Distinctive:

    Use properties when access behavior is truly needed.

    line 180
  52. Distinctive:

    Avoid dynamic attribute lookup in hot loops.

    line 181
  53. Distinctive:

    Prefer composition over complex inheritance.

    line 182
  54. Distinctive:

    Use dataclasses for simple immutable or mutable data records.

    line 183
  55. Very specific:

    Consider NamedTuple for lightweight, fixed records.

    line 184
  56. Distinctive:

    Use generators for lazy processing.

    line 196
  57. Distinctive:

    Avoid materializing a large iterator unless it must be reused.

    line 197
  58. Very specific:

    Use assert only for internal invariants.

    line 202
  59. Very specific:

    Never use assert for input validation.

    line 203
  60. Distinctive:

    Use explicit exceptions for bad user or API input.

    line 204
  61. Very specific:

    Avoid catching Exception unless the code can handle or re-raise it correctly.

    line 206
  62. Very specific:

    Avoid swallowing KeyboardInterrupt and SystemExit.

    line 207
  63. Distinctive:

    Add annotations to public APIs and complex functions.

    line 210
  64. Very specific:

    Prefer precise types over Any.

    line 212
  65. Very specific:

    Use typing.Protocol for structural interfaces.

    line 213
  66. Very specific:

    Run mypy, pyright, or another checker consistently.

    line 214
  67. Distinctive:

    Add unit tests for public behavior.

    line 218
  68. Distinctive:

    Add regression tests for bugs.

    line 219
  69. Distinctive:

    Test large inputs and boundary cases.

    line 221
  70. Distinctive:

    Run tests under standard and free-threaded builds when relevant.

    line 222
  71. Distinctive:

    Avoid micro-optimizations that make code harder to read without measurable benefit.

    line 223
  72. Distinctive:

    Import only modules needed at startup.

    line 226
  73. Distinctive:

    Use lazy imports for optional or rarely used dependencies.

    line 227
  74. Distinctive:

    Avoid work at module import time.

    line 228
  75. Distinctive:

    Use logging rather than print statements in libraries.

    line 229
  76. Distinctive:

    Use a virtual environment for dependencies.

    line 230
  77. Distinctive:

    Keep platform-specific code isolated.

    line 232
  78. Distinctive:

    Before merging a performance-sensitive piece of code:

    line 236

“Common” is measured: kept by at least 6 in 10 of the 47 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python Efficiency Checklist

1. Start with correctness

  • Use clear names and focused functions.
  • Follow PEP 8 and type hints where they improve maintenance.
  • Add tests before optimizing.
  • Use cProfile, time, tracemalloc, or benchmark tools to find real bottlenecks.
  • Don’t optimize code until a benchmark proves it is slow.

2. Choose the right data structure

  • Membership testing: use set or frozenset, not repeatedly searching a list.
  • Key/value lookup: use dict.
  • Append and pop from the end: use list.
  • Frequent insert/remove at both ends: use deque.
  • Unique and order-independent values: use set.
  • Immutable sequence: consider tuple.
  • Large text built repeatedly: use "".join(parts), not repeated +=.

3. Avoid repeated work

  • Move constant work outside loops.
  • Cache repeated function calls or expensive calculations.
  • Reuse a regex compiled with re.compile().
  • Use functools.lru_cache or functools.cache only for genuinely cacheable pure functions.
  • Avoid recalculating len(), attribute values or method calls in a tight loop.
# Avoid
for item in items:
    result.append(process(item))

# Prefer if process() is expensive only for certain items
for item in eligible_items:
    result.append(process(item))

4. Use local variables and built-ins

  • CPython local-variable access is faster than repeated global or attribute lookup.
  • Prefer built-in functions such as sum(), any(), all(), min(), max(), sorted(), enumerate() and zip().
# Less efficient
for i in range(len(items)):
    print(i, items[i])

# More efficient
for i, item in enumerate(items):
    print(i, item)

5. Prefer comprehensions when they improve clarity

  • Use list, dict and set comprehensions for simple transformations.
  • Avoid deeply nested comprehensions.
  • Use map() or filter() only if they are clearer or faster in context.
# Clear and usually efficient
names = [item.name for item in items if item.active]

6. Be careful with loops

  • Use break to stop early.
  • Avoid checking each item separately when vectorized or built-in operations exist.
  • Don’t modify a list, set or dict while iterating over it.
  • Use a copy or a separate result collection when values change.
result = []
for item in items:
    if item.valid:
        result.append(item.value)

7. Use context managers and resources

  • Use with for files, locks, sockets and database connections.
  • Close resources explicitly or let a context manager close them.
  • Stream large files instead of reading everything into memory.
with open("data.txt", encoding="utf-8") as file:
    for line in file:
        process(line)

8. Avoid unnecessary allocations

  • Avoid creating temporary lists when a generator is sufficient.
  • Don’t convert iterables to lists unless indexing or reuse requires it.
  • Reuse immutable objects where practical.
  • Use slices carefully; slicing creates a new object.
  • Prefer tuple unpacking and generator expressions for short-lived values.
# Generator; no intermediate list is allocated
sum(value * 2 for value in values)

9. Handle exceptions efficiently

  • Exceptions should represent exceptional cases, not normal control flow.
  • Catch specific exceptions.
  • Put exception handling around only the potentially failing operation.
try:
    value = mapping[key]
except KeyError:
    value = default

If there can be many misses, sometimes dict.setdefault() or defaultdict is better.

10. Avoid common string costs

  • Join strings instead of repeatedly concatenating.
  • Use f-strings for readable formatting.
  • Use prefix/suffix checks and membership efficiently.
  • Avoid parsing or splitting the same text repeatedly.
  • Normalize text once if it must be reused.
  • Use bytes only when binary data is intentional.
text = "".join(parts)

11. Optimize I/O

  • Batch database writes or reads.
  • Use connection pools for database or network resources.
  • Avoid holding large resources inside loops.
  • Use buffering for repeated file operations.
  • Do not perform network requests in nested loops unless necessary.

12. Control concurrency correctly

  • Use threading for I/O-bound tasks.
  • Use multiprocessing for CPU-bound parallel work.
  • Don’t assume threading will speed up Python CPU calculations in a standard GIL build.
  • Use async I/O for high-concurrency network or file tasks.
  • Protect shared mutable state with locks or synchronization primitives.
  • Prefer queues and messages over shared mutable objects.
  • Don’t create one lock or thread unnecessarily for every small operation.

13. Avoid unsafe or slow patterns

  • Avoid global mutable state.
  • Avoid excessive reflection or dynamic exec.
  • Avoid repeated import calls inside loops.
  • Don’t use mutable defaults:
# Avoid
def add(item, items=[]):
    ...
# Prefer
def add(item, items=None):
    if items is None:
        items = []
  • Avoid shallow assumptions about object copy behavior.
  • Avoid long chains of attribute lookup when used repeatedly.

14. Memory management

  • Remove large references when no longer needed.
  • Use generators for large sequences.
  • Be cautious with caches—they can grow indefinitely.
  • Use weak references for optional object tracking.
  • Call gc.collect() manually only for specialized needs, not routinely.
  • Avoid creating large temporary objects in comprehensions.
  • Use __slots__ only after measurement if many instances are created.
class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

15. Classes and objects

  • Keep classes focused and small.
  • Use properties when access behavior is truly needed.
  • Avoid dynamic attribute lookup in hot loops.
  • Prefer composition over complex inheritance.
  • Use dataclasses for simple immutable or mutable data records.
  • Consider NamedTuple for lightweight, fixed records.
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float

16. Generators and iterators

  • Use generators for lazy processing.
  • Avoid materializing a large iterator unless it must be reused.
  • Remember that generators execute only when consumed.
  • Close generators if they hold resources.

17. Debugging and safety

  • Use assert only for internal invariants.
  • Never use assert for input validation.
  • Use explicit exceptions for bad user or API input.
  • Return clear values or raise meaningful exceptions.
  • Avoid catching Exception unless the code can handle or re-raise it correctly.
  • Avoid swallowing KeyboardInterrupt and SystemExit.

18. Type hints

  • Add annotations to public APIs and complex functions.
  • Don’t spend effort annotating every trivial local.
  • Prefer precise types over Any.
  • Use typing.Protocol for structural interfaces.
  • Run mypy, pyright, or another checker consistently.
  • Type hints should describe the program, not change runtime behavior.

19. Testing

  • Add unit tests for public behavior.
  • Add regression tests for bugs.
  • Benchmark before and after optimization.
  • Test large inputs and boundary cases.
  • Run tests under standard and free-threaded builds when relevant.
  • Avoid micro-optimizations that make code harder to read without measurable benefit.

20. Packaging and startup

  • Import only modules needed at startup.
  • Use lazy imports for optional or rarely used dependencies.
  • Avoid work at module import time.
  • Use logging rather than print statements in libraries.
  • Use a virtual environment for dependencies.
  • Pin dependencies for reproducible deployments.
  • Keep platform-specific code isolated.

Practical review sequence

Before merging a performance-sensitive piece of code:

  1. Is it correct and readable?
  2. Are tests adequate?
  3. Are data structures appropriate?
  4. Are there unnecessary repeated loops or allocations?
  5. Are I/O and external calls batched?
  6. Are exceptions used for exceptional cases?
  7. Is there actual profiling evidence showing the current bottleneck?
  8. Does the optimization still make the code easier to maintain?

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.