2017-10-16 10 views
0

または、関数呼び出し自体を何らかの形でキャプチャすることは可能ですか(異なる引数にどの値が割り当てられているかを記述する)?ユーザー定義関数が呼び出されているかどうかの情報を追加することは可能ですか?

申し訳ありませんが、質問の貧弱な表現です。私はいくつかの再現性のあるコードで説明しましょう:

import pandas as pd 
import numpy as np 
import matplotlib.dates as mdates 
import inspect 

# 1. Here is Dataframe with some random numbers 
np.random.seed(123) 
rows = 10 
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB')) 
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist() 
df['dates'] = datelist 
df = df.set_index(['dates']) 
df.index = pd.to_datetime(df.index) 
#print(df) 

# 2. And here is a very basic function to do something with the dataframe 
def manipulate(df, factor): 
    df = df * factor 
    return df 

# 3. Now I can describe the function using: 
print(inspect.getargspec(manipulate)) 

# And get: 
# ArgSpec(args=['df', 'factor'], varargs=None, keywords=None, 
# defaults=None) 
# __main__:1: DeprecationWarning: inspect.getargspec() is 
# deprecated, use inspect.signature() or inspect.getfullargspec() 

# 4. But what I'm really looking for is a way to 
# extract or store the function AND the variables 
# used when the function is called, like this: 
df2 = manipulate(df = df, factor = 20) 

# So in the example using Inspect, the desired output could be: 
# ArgSpec(args=['df = df', 'factor = 10'], varargs=None, 
# and so on... 

私はこれは少し奇妙なように見えるかもしれないが、それは実際にこのような何かを行うことができるようにするため、私にはとても便利だと実感。誰かが興味を持っていれば、私がデータ・サイエンスのワークフローにどのように適合するかなど、すべてをより詳細に説明することができます。

ありがとうございます!

答えて

1

することはできbind the parameters to the function and create a new callable

import functools 
func = functools.partial(manipulate, df=df, factor=20) 

結果partialオブジェクトは、属性argskeywords使用して引数の検査と修正ができます:

func() 
を使用して

func.keywords # {'df': <pandas dataframe>, 'factor': 20} 

と、最終的に呼び出すことができます

関連する問題