争论的打印名称输入功能在Python [英] Print name of argument typed in functions in Python

查看:122
本文介绍了争论的打印名称输入功能在Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情

def myfunc(list):

当我打电话的功能,我可以象

When I call the function, I can type like

myfunc(List1)

有一种方法可以打印出输入作为函数的参数列表?
是这样的:

There is a way to print out the list typed as argument in the function? Something like:

def myfunc(list):
    print (list.name)

这将使:

myfunc(List1)
List1

感谢您提前

推荐答案

在一个变种建议欧米 - saadon ,就是用的 inspect.getframeinfo 其中列出了code_context。

A variant over the one suggested by omri-saadon, is to use inspect.getframeinfo which lists the code_context.

import inspect

def debug(*args):

    try:  # find code_context

        # First try to use currentframe() (maybe not available all implementations)
        frame = inspect.currentframe()
        if frame:
            # Found a frame, so get the info, and strip space from the code_context
            code_context = inspect.getframeinfo(frame.f_back).code_context[0].strip()
        else:

            # No frame, so use stack one level above us, and strip space around
            # the 4th element, code_context
            code_context = inspect.stack()[1][4][0].strip()

    finally:
         # Deterministic free references to the frame, to be on the safe side
         del frame

    print('Code context: {}'.format(code_context))
    print('Actual arguments: {}'.format(args))


## Test code to have something to output #########
def my_seventh():
   return 7

a = 0.2
b = 1.2
c = a + 1
my_eight = my_seventh

debug(a, b, c, b+2)
debug([4.1, 4.2], (5.1, 5.2), {6.1: 6.2}, my_seventh, my_eight, my_eight())

my_list = [1, 2, 3, 4, 5]

def first_level():
    def second_level():
         debug(my_list[:2],
               my_list[3:])

    second_level()

first_level()

运行此code时,输出为:

Output when running this code is:

Code context: debug(a, b, c, b+2)
Actual arguments: (0.2, 1.2, 1.2, 3.2)
Code context: debug([4.1, 4.2], (5.1, 5.2), {6.1: 6.2}, my_seventh, my_eight, my_eight())
Actual arguments: ([4.1, 4.2], (5.1, 5.2), {6.1: 6.2}, <function my_seventh at 0x102294488>, <function my_seventh at 0x102294488>, 7)
Code context: my_list[3:])
Actual arguments: ([1, 2], [4, 5])

在换句话说,使用的检查方案,以获得frameinfo会给你触发您的函数调用的源代码行(或其最后一行)。但是,如果实际通话拆分为多行,只有最后一行给出code上下文。到目前为止我还没有找到一种方法来在code上下文中的命名变量连接到实际参数。

In other words, using the inspect options to get the frameinfo will give you the source line (or last line thereof) which triggered your function call. However if the actual call is split over multiple lines, only the last line is given as code context. And so far I've not found a way to connect the named variables in the code context to the actual arguments.

这篇关于争论的打印名称输入功能在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆