LoginSignup
4
1

More than 5 years have passed since last update.

python print たぶん必要ないオレオレコード

Last updated at Posted at 2018-05-31

たぶん必要ないオレオレクソコード

不勉強なせいで多分必要だと思って書いてしまったシリーズ.

print


print('x=',x)

これをどうにかしたい.IDEとかでなくて(例えばjupyterとか)で,上記のように書くのが面倒でスニペットが使えないとき.

print1

今の所,これが一番いい.他の手法は,xを全部文字列としてタイプしているけど,これは,変数名を取得しているのでその文楽になる.

def print1(x,non_break=True):

    import inspect
    import re

    # この関数の呼び出し元のフレームオブジェクトを取得
    bac_frame = inspect.currentframe().f_back

    # 呼び出し元のソースコードのリストからstring.whitespace(' \t\n\r\v\f')を削除して1行を取得
    bac_code = inspect.getframeinfo(bac_frame).code_context[0].replace(" ", "")

    # コメントの開始位置を取得
    pos = bac_code.find("#")  
    if pos != -1:
        bac_code = bac_code[:pos]  # コメントがあるとき削除
    name = re.search(r"\((.+)\)", bac_code).group(1)  # 呼び出し元関数の引数の変数名を取得

    if non_break == True: print(name + " = {}".format(x))
    else: print(name + " = {}\n".format(x))

x = np.arange(10)
print1(x)
print1(x.shape)
print1(np.arange(10))

# 出力
# x = [0 1 2 3 4 5 6 7 8 9]
# x.shape = (10,)
# np.arange(10) = [0 1 2 3 4 5 6 7 8 9]

print2

print2内で文字列が定義されていないから,呼び出しされた名前空間内の変数をグローバルとして取得する.

# def print2(s): exec('print(\'{0} = {{}}\'.format({0}))'.format(s)) #修正
def print2(s): print('{} == {}'.format(s, eval(s)))
def print2(s): print(f'{s} == {eval(s)}') # python3.6以降

x = np.arange(10)
print2('x')
print2('x.shape')

# 出力
# x = [0 1 2 3 4 5 6 7 8 9]
# x.shape = (10,)

python3.6以降

フォーマット済み文字列リテラル( formatted string literal )というらしい

x = np.arange(10)
print('x == {x}')
print(f'x == {x}')

# 出力
# x == {x}
# x == [0 1 2 3 4 5 6 7 8 9]

locals()を使う場合

できてないけど,.

x = np.arange(10)
print('x = {x}'.format(**locals()))

# 出力
# x = [0 1 2 3 4 5 6 7 8 9]
x = np.arange(10)
s="x"
s2 = ('print(\'{0} = {{0}}\'.format(locals()))'.format(s))
print('x = {0}'.format(locals()))
exec(s2)

#出力
print('x = {0}'.format(locals()))
exec(s2)はエラーが出る
4
1
2

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
4
1