Here's a complete, production-ready Python command-line tool that meets your requirements. I've named it pyfind and designed it to be intuitive, robust, and efficient. The code includes detailed comments and error handling, and it uses only standard library modules.
Features Implemented
- Fuzzy search across function names and docstrings
- Covers built-ins and key standard library modules
- Natural language-friendly with relevance ranking
- Graceful error handling for missing modules
- Clean, numbered output with function names and descriptions
- No external dependencies or configuration files
Installation
Save the script as pyfind (no extension), make it executable (chmod +x pyfind), and place it in a directory in your $PATH (e.g., /usr/local/bin/).
The Code
#!/usr/bin/env python3
import sys
import inspect
import builtins
import importlib
import re
from typing import List, Tuple, Dict, Any
# List of standard library modules to search
SEARCH_MODULES = [
'os', 'sys', 'pathlib', 'shutil', 'glob', 're', 'json', 'datetime',
'time', 'collections', 'itertools', 'random', 'math', 'functools'
]
def load_module_functions(module_name: str) -> Dict[str, Any]:
"""
Load functions from a module, handling import errors gracefully.
Returns a dictionary of function names to function objects.
"""
functions = {}
try:
module = importlib.import_module(module_name)
for name, obj in inspect.getmembers(module):
if inspect.isfunction(obj) or inspect.isbuiltin(obj):
functions[f"{module_name}.{name}"] = obj
except ImportError:
pass # Skip modules that can't be imported
return functions
def load_builtins() -> Dict[str, Any]:
"""
Load built-in functions.
Returns a dictionary of function names to function objects.
"""
functions = {}
for name, obj in inspect.getmembers(builtins):
if inspect.isfunction(obj) or inspect.isbuiltin(obj):
functions[name] = obj
return functions
def get_function_description(func: Any) -> str:
"""
Extract a one-line description from a function's docstring.
"""
doc = inspect.getdoc(func)
if not doc:
return "No description available"
# Take the first line of the docstring, strip it, and limit length
first_line = doc.split('\n')[0].strip()
return first_line[:80] # Truncate long descriptions
def score_match(query_terms: List[str], func_name: str, description: str) -> float:
"""
Score how well a function matches the query based on name and description.
Higher scores indicate better matches.
"""
score = 0.0
func_name_lower = func_name.lower()
description_lower = description.lower()
for term in query_terms:
term_lower = term.lower()
# Exact match in function name is a strong signal
if term_lower in func_name_lower:
score += 10.0
if func_name_lower.startswith(term_lower):
score += 5.0 # Bonus for prefix match
# Match in description is a weaker signal
if term_lower in description_lower:
score += 3.0
return score
def search_functions(query: str) -> List[Tuple[str, str, float]]:
"""
Search for functions matching the query.
Returns a list of (function_name, description, score) tuples.
"""
# Split query into terms, removing punctuation and extra whitespace
query_terms = re.findall(r'\w+', query.lower())
if not query_terms:
return []
# Load all functions to search
all_functions = load_builtins()
for module_name in SEARCH_MODULES:
all_functions.update(load_module_functions(module_name))
# Collect matches with scores
matches = []
for func_name, func in all_functions.items():
description = get_function_description(func)
score = score_match(query_terms, func_name, description)
if score > 0: # Only include functions with some relevance
matches.append((func_name, description, score))
# Sort matches by score (descending) and then alphabetically by name
matches.sort(key=lambda x: (-x[2], x[0]))
return matches
def display_results(matches: List[Tuple[str, str, float]]) -> None:
"""
Display search results in a clean, numbered format.
"""
if not matches:
print("No matching functions found.")
return
for i, (func_name, description, _) in enumerate(matches, 1):
# Format output with fixed-width function name column
print(f"{i}. {func_name:<25} {description}")
def main() -> None:
"""
Main entry point for the command-line tool.
"""
if len(sys.argv) < 2:
print("Usage: pyfind <search terms>")
print("Example: pyfind list files")
sys.exit(1)
# Join all arguments into a single query string
query = ' '.join(sys.argv[1:])
matches = search_functions(query)
display_results(matches)
if __name__ == "__main__":
main()