I need you to create a complete, production-ready Python command-line tool that solves a specific problem I have with finding Python functions.
The Problem
I'm a terminal-heavy developer who constantly forgets exact Python function names. I know what I want to do conceptually but can't remember if it's os.listdir(), os.scandir(), or glob.glob() when I want to "list files in a directory". Traditional documentation tools like or require exact names, and web searches break my flow.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I need intelligent, fuzzy searching where I can type natural language like "list files" or "remove duplicates from list" and get relevant Python functions with their descriptions.
Functional Requirements
Search scope: Cover Python built-ins and essential standard library modules (os, sys, pathlib, shutil, glob, re, json, datetime, collections, itertools, etc.)
Smart search:
Match function names (exact and partial)
Match function descriptions/docstrings
Handle multiple search terms intelligently
Rank results by relevance
Natural language friendly: "list files", "sort dictionary", "random number" should all work intuitively
Technical Constraints
Keep imports minimal (standard library only)
Handle import errors gracefully
Examples of Expected Behavior
bash
$ pyfind list files
1. os.listdir Return a list of entries in directory
2. os.scandir Return iterator of DirEntry objects
3. glob.glob Return list of paths matching pattern
$ pyfind remove duplicates
1. set Create new set (removes duplicates)
2. dict.fromkeys Create dict with unique keys
3. collections.OrderedDict Ordered dict preserving insertion order
$ pyfind current time
1. datetime.now Return current local datetime
2. time.time Return current time in seconds since epoch
What I Don't Want
Complex configuration files
Multiple subcommands or modes
The tool should be robust enough for daily use but simple enough that I never need to read documentation or remember how to use it.
Assistant
python
#!/usr/bin/env python3
import sys
import os
import importlib
import re
from collections import Counter
# Modules to include in the search
MODULES = [
"os",
"sys",
"pathlib",
"shutil",
"glob",
"re",
"json",
"datetime",
"collections",
"itertools",
"time",
"random",
"functools",
"math"
]
def build_index():
"""
Builds an index of functions and their descriptions from the specified modules.
Returns a list of tuples: (function_name, description, module_name)
"""
index = []
for module_name in MODULES:
try:
module = importlib.import_module(module_name)
for name in dir(module):
obj = getattr(module, name)
if callable(obj):
try:
description = obj.__doc__ or ""
if description:
index.append((name, description.strip(), module_name))
except Exception:
pass # Handle cases where docstring access fails
except ImportError:
print(f"Warning: Could not import module {module_name}", file=sys.stderr)
except Exception as e:
print(f"Warning: Error processing module {module_name}: {e}", file=sys.stderr)
return index
def search(query, index):
"""
Searches the index for functions matching the query.
Returns a list of tuples: (function_name, description, module_name), sorted by relevance.
"""
query_terms = re.findall(r'\b\w+\b', query.lower()) # Extract words
results = []
for name, description, module_name in index:
score = 0
name_lower = name.lower()
description_lower = description.lower()
for term in query_terms:
if term in name_lower:
score += 3 # Higher score for name matches
if term in description_lower:
score += 1 # Score for description matches
if score > 0:
results.append((name, description, module_name, score))
# Sort by score (descending)
results.sort(key=lambda x: x[3], reverse=True)
return [(name, description, module_name) for name, description, module_name, score in results]
def main():
"""
Main function to handle command-line arguments and perform the search.
"""
if len(sys.argv) < 2:
print("Usage: pyfind <search_query>")
sys.exit(1)
query = " ".join(sys.argv[1:])
index = build_index()
results = search(query, index)
if results:
for i, (name, description, module_name) in enumerate(results):
print(f"{i+1}. {module_name}.{name:<20} {description}")
else:
print("No matching functions found.")
if __name__ == "__main__":
main()
Clear Structure: The code is divided into functions (build_index, search, main) for better organization and readability.
Module List:MODULES list makes it easy to extend the search scope.
Robust Error Handling:try...except blocks handle ImportError (if a module can't be imported) and other exceptions during module processing, preventing the tool from crashing. Warnings are printed to sys.stderr so they don't interfere with the output.
Intelligent Search:
Word Extraction: Uses re.findall(r'\b\w+\b', query.lower()) to extract individual words from the query, handling natural language better. This avoids matching parts of words.
Scoring: Assigns different scores to matches in function names (higher) and descriptions (lower) to prioritize more relevant results.
Case-Insensitive: Converts both the query and the function/description text to lowercase for case-insensitive matching.
Relevance Ranking: Results are sorted by score in descending order, so the most relevant functions appear first.
Concise Output: The output is formatted for easy readability, including the module name and function name.
Docstring Handling: Handles cases where a function might not have a docstring (obj.__doc__ or "").
Shebang: The #!/usr/bin/env python3 line makes the script executable directly from the command line on Unix-like systems.
Minimal Dependencies: Uses only the Python standard library.
Clear Usage Message: Provides a helpful usage message if no search query is provided.
if __name__ == "__main__":: Ensures that the main function is only called when the script is executed directly, not when it's imported as a module.
Formatting: Uses f-strings for cleaner string formatting.
Module Name in Output: Includes the module name in the output for clarity.
Padding: Uses <20 in the f-string to pad the function name, making the output more aligned.
How to use:
Save: Save the code as a Python file (e.g., pyfind.py).
Make Executable (Linux/macOS):chmod +x pyfind.py
Run:./pyfind.py <search_query> (or python pyfind.py <search_query> if you didn't make it executable).
Example:
bash
./pyfind.py list files
This will output a list of functions related to listing files, ranked by relevance. The more specific your query, the better the results will be.