有关如何调用用户定义函数的外部信息是否可能?

时间:2017-10-16 12:41:11

标签: python

或者是否可以以任何方式捕获函数调用本身(描述哪些值分配给不同的参数)?

对不起这个问题的措词不好。让我用一些可重现的代码来解释:

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 个答案:

答案 0 :(得分: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.keywords  # {'df': <pandas dataframe>, 'factor': 20}

和最终可以使用

调用
func()