4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでprint()の改造

Last updated at Posted at 2019-02-02

やりたいこと

関数を別名に退避しておき、既存関数を再定義する
print()ではあとから出力内容を整形したいな、というときに使う。

コード

hogehoge.py
# -*- coding: utf-8 -*-
import datetime

# printをppprintへ退避
ppprint = print

# printを再定義
def print(*args, **kwargs):
    try:
        ppprint(str(datetime.datetime.now())+":::", end="")
        ppprint(*args, **kwargs)
    except Exception as e:
        ppprint(*args,**kwargs)

print("qiita")

実行結果

> 2019-02-02 11:56:16.296658:::qiita

※2019.02.10 追記

グローバル変数を汚さないやり方をコメントで教えていただきました

デフォルト引数を使う方法
デフォルト引数は関数定義時に一度だけ評価されるので、元のprintをずっと覚えていられます。

import datetime

# printを再定義
def print(*args, print_=print, **kwargs):
    try:
        print_(str(datetime.datetime.now())+":::", end="")
        print_(*args, **kwargs)
    except Exception as e:
        print_(*args,**kwargs)

print("qiita")

組込み情報を参照する方法

import datetime

# printを再定義
def print(*args, **kwargs):
    try:
        __builtins__.print(str(datetime.datetime.now())+":::", end="")
        __builtins__.print(*args, **kwargs)
    except Exception as e:
        __builtins__.print(*args,**kwargs)

print("qiita")
4
4
1

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?