2
1

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 1 year has passed since last update.

Python 関数名を取得する

Last updated at Posted at 2022-03-19

pythonのオブジェクト

def my_func():
    return 

print(my_func.__name__)
'my_func'

使用例

マルチスレッドの実行時にタスク名(関数名)をスレッド名にする

from threading import Thread

def task1():
    while True:
        break

def task2():
    while True:
        break

task_list = [task1,task2]
for task in task_list:
    th = Thread(target=task, args=(), daemon=True, name=task.__name__)
    th.start()

wrapperにして使う

@shiracamusさんにコメントいただきました。

def greet(callback):
    print("Hello", callback.__name__)
    callback()

def taro():
    print("Hi, I'm Taro.")

def hanako():
    print("Hello, this is Hanako.")

greet(taro)
greet(hanako)
実行結果
Hello taro
Hi, I'm Taro.
Hello hanako
Hello, this is Hanako.
2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?