一键导入
python
Style guide for writing Python code matching the user's personal conventions. Use when writing, reviewing, or modifying Python scripts and modules.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Style guide for writing Python code matching the user's personal conventions. Use when writing, reviewing, or modifying Python scripts and modules.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Remove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on Wikipedia's comprehensive "Signs of AI writing" guide. Detects and fixes patterns including: inflated symbolism, promotional language, superficial -ing analyses, vague attributions, em dash overuse, rule of three, AI vocabulary words, passive voice, negative parallelisms, and filler phrases.
Style guide for writing bash scripts matching the user's personal conventions. Use when writing, reviewing, or modifying bash/shell scripts.
A test data pattern for Kotlin/Java that uses an Object Mother class with an inner Builder to produce readable, flexible, and consistent test fixtures. Use when writing or refactoring tests that need domain objects.
| name | python |
| description | Style guide for writing Python code matching the user's personal conventions. Use when writing, reviewing, or modifying Python scripts and modules. |
Write Python code following these conventions:
#!/usr/bin/env python3 for executable scripts#!/usr/bin/env -S uv run --scriptfrom functools import cache) over module imports when only one thing is usedsnake_case with verb prefixes (get_, create_, find_, parse_, list_, describe_)__profile_namerPascalCaseUPPER_SNAKE_CASEsnake_case, single letters fine for loop vars (i, k, m)PascalCase with Exception/Error suffixlist[str], dict[str, int], tuple[bytes], X | None'''view the file in a pager''''hello', 'utf-8' - unless running in python3 -c $'', in which case use double quotesf'Creating {name}'% formatting inside logging calls: logging.info('Creating %s', name)r'\[([^]]+)\]'Exception — keep them simple:
class SocketClosedException(Exception): pass
raise Exception(...) is fine for one-off errors in scriptsraise ... from e to chain exceptions with contextassert for internal invariant/precondition checksNotImplementedError for unhandled cases/branches and abstract methodsexcept: with logging and re-raise is acceptable for response hooks / middlewareBaseExceptionGroup for collecting multiple errors:
if exceptions := [f.exception() for f in futures if f.exception()]:
raise BaseExceptionGroup('failed', exceptions)
KeyboardInterrupt (POSIX convention)@dataclass for simple data containers; regular classes for behavior-heavy types:@dataclass(kw_only=True, eq=False) when keyword-only construction and identity semantics are neededEnum for status codes and protocol constants:@classmethod for factory methods (from_args, from_str, from_uri)@staticmethod for methods that don't need instance state@cache liberally for memoization of expensive calls, use this as much as possible to avoid writing own memo/state in code@contextlib.contextmanager for resource lifecycle management__getattr__ for dynamic method dispatch and lazy module wrapperspartial from functools for creating function aliases, in thread code, etc
log = partial(print, file=sys.stderr)
lambda for simple inline callbacksNotImplementedError:
def user_status(self, user) -> Status:
raise NotImplementedError
defaultdict when accumulating into groups or building lookup tablesdatetime objects (e.g., from AWS responses), use a custom default handler:
def json_dumper(x):
if isinstance(x, datetime.datetime):
return x.timestamp()
return json.JSONEncoder().default(x)
print(json.dumps(summary, default=json_dumper))
ExceptionGroup / BaseExceptionGroup for multiple errorsmatch/case where appropriatepathlib.Path preferred over os.pathor: assignees = assignees or []data = {'title': title, **kwargs}requests.Session() for connection reuseSESSION = requests.Session()
def response_hook(response, *args, **kwargs):
try:
logging.debug('Making %s request to: %s with body: %r', response.request.method, response.request.url, response.request.body)
response.raise_for_status()
except:
logging.error('Failed %s request to %s', response.request.method, response.request.url)
logging.error('%s', response.text)
raise
SESSION.hooks = {'response': response_hook}
SESSION.get(...), SESSION.post(...) etc. without per-call error checkingasyncio for concurrent I/O — async/await with asyncio.gather for parallelismargparse with subparsers for multi-command toolsif __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(130)
BrokenPipeError handling when output may be piped--log with choices debug, info, warning, error, criticalparser.error() for complex constraintsparse_known_args when passing extra args through to other commandsparser.set_defaults(callback=...) for subcommand dispatchlogging module — configure in main():
parser.add_argument(
'-l',
'--log',
choices=('debug', 'info', 'warning', 'error', 'critical'),
default='info',
help='Logging level (default: %(default)s)',
)
level = getattr(logging, args.log.upper())
logging.basicConfig(level=level, format='%(levelname)s\t%(message)s')
logging.basicConfig(level=logging.INFO, format='%(levelname)s\t%(message)s') at top of fileprint(..., file=sys.stderr) is also fine for simple scripts% style in log calls (not f-strings): logging.info('Creating %s', name)logging.exception() for caught exceptions with tracebackboto3.set_stream_logger('boto3', level=level + 1)ThreadPoolExecutor for parallel I/O operationsScopedThreadPoolclass ScopedThreadPool(ThreadPoolExecutor):
"""
Wrapper around ThreadPoolExecutor that ensures all futures are completed before exiting the context
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.futures = []
def submit(self, *args, **kwargs):
future = super().submit(*args, **kwargs)
self.futures.append(future)
return future
def __exit__(self, *args, **kwargs):
while True:
done, pending = wait(self.futures)
# may have futures that creates more futures
if len(done) == len(self.futures):
break
result = super().__exit__(*args, **kwargs)
if exceptions := [f.exception() for f in self.futures if f.exception()]:
if len(exceptions) == 1:
raise exceptions[0]
raise BaseExceptionGroup('failed', exceptions)
return result
with ScopedThreadPool() as executor:
executor.submit(func)
with ScopedThreadPool() as executor:
for region in {'ap-southeast-2', 'us-east-1'}:
@executor.submit
def job(region=region):
print(region)
uv as package manager for modern projectsunittest.TestCase with test_* methods when tests existself.assertEqual(), self.assertRaises() for assertionssetattr(TestClass, 'test_' + name, fn) for parameterized tests