The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a code snippet reuse tracker

Here’s a simple Code Snippet Reuse Tracker implemented in Python. It tracks snippets you save, lets you reuse them by keyword, and keeps usage stats so you know which snippets you use most.

python
class SnippetTracker: def __init__(self): self.snippets = {} self.usage_count = {} def add_snippet(self, keyword, code): """Add a new snippet with a unique keyword.""" if keyword in self.snippets: print(f"Snippet with keyword '{keyword}' already exists.") else: self.snippets[keyword] = code self.usage_count[keyword] = 0 print(f"Snippet '{keyword}' added.") def get_snippet(self, keyword): """Retrieve a snippet by keyword and update usage count.""" if keyword in self.snippets: self.usage_count[keyword] += 1 return self.snippets[keyword] else: print(f"No snippet found for keyword '{keyword}'.") return None def list_snippets(self): """List all stored snippets.""" if not self.snippets: print("No snippets stored.") return print("Stored snippets:") for k in self.snippets: print(f" - {k} (used {self.usage_count[k]} times)") def top_used(self, n=3): """Show top n most used snippets.""" sorted_usage = sorted(self.usage_count.items(), key=lambda x: x[1], reverse=True) print(f"Top {n} most used snippets:") for keyword, count in sorted_usage[:n]: print(f"{keyword}: used {count} times") # Example usage: tracker = SnippetTracker() tracker.add_snippet("hello_world", "print('Hello, world!')") tracker.add_snippet("factorial", "def factorial(n): return 1 if n==0 else n*factorial(n-1)") print(tracker.get_snippet("hello_world")) print(tracker.get_snippet("factorial")) print(tracker.get_snippet("hello_world")) tracker.list_snippets() tracker.top_used()

This basic tracker lets you:

  • Add snippets under a keyword

  • Retrieve snippets by keyword and count usage

  • List all snippets with usage counts

  • See the top most used snippets

You can extend it with saving/loading from a file, searching by partial keyword, or tagging snippets. Want me to help with that?

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About