LoginSignup
2
1

More than 3 years have passed since last update.

Pythonの試行で使用する.pyファイルの定型(テンプレート) - 2020年

Last updated at Posted at 2020-12-30

Pythonの試行で使用する.pyスクリプトの定型コード(テンプレート)。以下、定型.pyの欄を参照。

コードのスタイル

run__main1()等で、複数の試行処理を分けて書き、main()関数内でrun__main1()等をコメント/コメントアウトで切り替えて、実行する関数を切り替えるスタイル。コーディング時、エディタ内で関数名run__main1等を検索・ジャンプして、main()関数内の切り替え状態を確認、もう一度ジャンプすると元のrun__main1関数位置まで戻って、編集続行するスタイル。

関数は、def func1(x,の上のコメント# ○○の機能のように、関数定義の上の行に、その関数の簡単な(特徴的な)説明を付加するスタイル。関数のすぐ下には、def test__func1():のようにテスト関数(機能が単独で確認できる実行コード)を常に合わせて書いておくスタイル。テスト関数のコードが、その関数の代表的な使い方を表すコード例にもなるのでなお有用。テスト関数は、# main = test__func1のように、mainを上書きする形で実行させるスタイル。このテスト関数の実行時は、コメントを外してmain = test__func1とすることで、テスト関数test__func1のみが実行されるように切り替わる。

matplotlibのグラフの定型コード、numbaの高速化の定型コード、を末尾に付随、不要なものは要削除。

コードの構成

image.png

ソースコード 定型.py

定型.py

# -*- coding: utf-8 -*-

# ○○の試行

# 結果: ○○

# import例: (不要なものは要削除)
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numba

# sec: main

def main(): # 実行切替用
    run__main1()
    # run__main2()
    # run__main3()

# ○○の試行
def run__main1():
    # 結果: ○○

    # sec: config

    pass

    # sec: run

    pass

    # sec: draw

    pass

"""コンソール出力例:
○○
"""

# ○○の試行
def run__main2():
    pass

# ○○の試行
def run__main3():
    pass


# sec: ○○の機能

# ○○の機能
def func1(x, # 必須引数の説明1
    y = 0, # オプションの説明1
    z = 0): # オプションの説明2
    pass

def test__func1():
    pass
# main = test__func1


# sec: グラフ定型

def draw__main1():
    fig = plt.figure(tight_layout=True)
    ax = fig.add_subplot(111)
    ax.plot((0, 1), (2, 3), "r-o")
    ax.grid()
    # ax.annotate("test", xy=(0.2, 2.2), ha='left', va='top')
    # ax.axis("equal")
    # ax.legend(fontsize=9, framealpha=0.5, labelspacing=0.2)
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    fig.savefig("test.png")
    plt.show()

# sec: Numba定型

@numba.jit(nopython=True, nogil=True, cache=True) # 高速化部のみ関数を分離 約50倍高速に
def numba_func(x):
    pass

# sec: entry

if __name__ == "__main__": main()
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1