DEV Community

Tomoyuki KOYAMA
Tomoyuki KOYAMA

Posted on

Cheat sheet for development in Python

Snippet

Environemnt Variables

import os

os.getenv("ENV_VAR_NAME", "default_value")
Enter fullscreen mode Exit fullscreen mode

os — Miscellaneous operating system interfaces — Python 3.12.3 documentation

Command Line Argument

import argparse

parser = argparse.ArgumentParser(description='Parse command line options.')
parser.add_argument('integers', metavar='c', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args(['--sum', '7', '-1', '42'])
print(args.accumulate(args.integers))
Enter fullscreen mode Exit fullscreen mode

argparse — Parser for command-line options, arguments and sub-commands — Python 3.12.3 documentation

Random number

import random
x = random.randint(0, 100) # 0 <= x <= 100
Enter fullscreen mode Exit fullscreen mode

Logging

from logging import basicConfig, getLogger, DEBUG

# put in entry point file
CHAR_GREEN = '\033[32m'
CHAR_RESET = '\033[0m'
FORMAT = f"{CHAR_GREEN}%(asctime)s %(levelname)s %(name)s {CHAR_RESET}: %(message)s"
basicConfig(level=INFO, format=FORMAT)

# put in all files
logger = getLogger(__name__)

# logging code
logger.info('hello')
Enter fullscreen mode Exit fullscreen mode

Ref: ログ出力のための print と import logging はやめてほしい #Python - Qiita

Packages

Code formatter

Install packages

pip install \
  black \
  autopep8 \
  isort \
  ;
Enter fullscreen mode Exit fullscreen mode

Run installed packages

black .
autopep8 --recursive --in-place --aggressive --aggressive .
isort .
Enter fullscreen mode Exit fullscreen mode

Package Manager

Poetry

Setup project

cd <project_root>
poetry init
Enter fullscreen mode Exit fullscreen mode

Add a package

poetry add <package_name>
Enter fullscreen mode Exit fullscreen mode

Install dependencies using poetry

poetry install
Enter fullscreen mode Exit fullscreen mode

venv

Create venv

python -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Activate venv

source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Install package

pip install <package_name>
Enter fullscreen mode Exit fullscreen mode

pyenv

Check installed version list

pyenv versions
Enter fullscreen mode Exit fullscreen mode

Get version list

pyenv install -l
Enter fullscreen mode Exit fullscreen mode

Install specific version

pyenv install <python_version>
Enter fullscreen mode Exit fullscreen mode

Get global version

pyenv global
Enter fullscreen mode Exit fullscreen mode

Get local version

pyenv local
Enter fullscreen mode Exit fullscreen mode

Top comments (0)