LoginSignup
18
16

More than 5 years have passed since last update.

[Python] 関数内からその関数の名前を取得する方法

Last updated at Posted at 2018-06-19

本題

Pythonでたまにタイトルのようなことがしたくなるのでメモ

結論から言うとsys._getframe().f_code.co_nameを使う

import sys

def hoge():
    print(sys._getframe().f_code.co_name)

hoge()
# -> hoge

応用例

例えば、自作クラスのメンバ変数を全て格納した辞書型を出力するメンバ関数を作る時に使う。

# 例: 「<-」で示したものだけ出力したい
dir(obj) ->
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'age',              # <-
 'name',             # <-
 'saveAsDict']

nameageをメンバ引数に持つPersonでやってみる

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def asDict(self):
        out = dict()
        for attr in dir(self):
            # ↓ここで使用
            if not ("__" in attr or callable(attr) or attr is sys._getframe().f_code.co_name):   
                out[attr] = getattr(self, attr)
        return out

shinzo = Person("Abe", 63)
print(shinzo.asDict())
# -> {'age': 63, 'name': 'Abe'}

元も子もなく

メンバ関数じゃなければsys._getframe().f_code.co_nameを使う必要はない

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def asDict(obj):
    out = dict()
    for attr in dir(obj):
        if not ("__" in attr or callable(attr)):  # <- 3つめの項目を削除
            out[attr] = getattr(obj, attr)
    return out

shinzo = Person("Abe", 63)
print(asDict(shinzo))
# -> {'age': 63, 'name': 'Abe'}
18
16
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
18
16