基本的な方針

これだけ多くの人に使われているにもかかわらず,環境構築の難易度がとても高いことで悪名高いPython について,私は各プロジェクトごとに特定バージョンのPythonを入れることにした.特定バージョンのPythonを管理するのには mise を使っている。 mise はPython以外のプログラミング言語やCLIツールの管理もできる。バージョンの固定が重要なものは homebrew ではなくこちらを使うことが多い。生成AI時代ではnpm系のAIコーディングエージェントもこれで管理している。

Pythonプロジェクト中の依存パッケージ管理は uv に落ち着いた。以前はPoetryやRyeなど使っていたが、長年の混沌に終止符が打たれたような気持ち。 細かいことを言うと、uv 自体が Python バージョンの管理も可能なので、 mise でインストールしているのは Python そのものではなく uv だったりする。

Tips

-u オプションでpythonファイルを実行すると,標準出力がバッファされずに直ちに出力される

python -u <script> | tee <file>

ちなみに, print() 関数の flush オプションでも可能. Carriage Return と組み合わせると,簡単な進捗状況の表示もできる.

print("string", '\r', end='', flush=True)

pathlib 早見表

from pathlib import Path
 
p = Path()  # => current dir
 
for i in p.iterdir():  # or p.glob('**/*.py')
    if i.is_file():
        # do something
        p.name  # => hoge.txt
        p.stem  # => .../hoge.txt -> hoge
        p.suffix  # => hoge.txt -> hoge
        p / 'subdir' # => Path('./subdir')

logging の使い方

引用元:

ライブラリ側

import logging
logger = logging.getLogger(__name__)
 
def do():
  # do sth
  logger.debug("testtest")

ユーザ側

ログが欲しいモジュールごとにgetLoggerを設定すればよい。
パッケージの全てのモジュールのログを出したいときは “my_pkg” とする。

import logging
 
from my_pkg import mod01
 
logging.basicConfig()  # level=logging.WARNING
logging.getLogger("my_pkg.mod01").setLevel(level=logging.INFO)

logの内容をlogファイルに書き込むと同時にsys.stderrにも書き込む場合。
ファイルと標準エラー出力でログレベルを変えられる。
basicConfigでデフォルトのログ出力先をファイルにした上で、
getLoggerで得たモジュールレベルのloggerに標準エラー出力のHandlerを追加している。

import logging
from my_pkg import mod01, mod02
 
# DEBUG+ to a file
logging.basicConfig(
    level=logging.DEBUG,
    filename="./sample.log"
)
 
# INFO+ to STDERR
console = logging.StreamHandler()  # => sys.stderr
console.setLevel(logging.INFO)
# Below first activates `basicConfig`, then add `console`
logging.getLogger("my_pkg.mod01").addHandler(console)
# logging.getLogger("my_pkg.mod02").addHandler(console)

A handy decorator to print all arguments of the given function

**kwargs で関数に入力されるキーワード引数も動的にしているときのデバッグに役立つデコレータ.

def logargs(func):
    """Print debugging for (kw)args.
 
		Usage:
        @logargs
				def a_func_to_check(a, b, **kwargs): pass
		"""
    def inner(*args, **kwargs):
        print(*args)
        print(**kwargs)
        return fun(*args, **kwargs)
    return inner

Rate limit handling for Web API

twython を使った例. while True というナンセンスなループの中に閉じ込めないといけない.

while True:
    try:
        tl_tweets = twitter.get_user_timeline(
            screen_name=row['screen_name'],
            max_id=row['id']
        )
    except TwythonRateLimitError:
        print('sleep 15 min due to the rate limit', file=sys.stderr)
        time.sleep(60 * 15 + 5)
        continue
    break