将变量名转换为字符串? [英] Convert Variable Name to String?

查看:54
本文介绍了将变量名转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 python 变量名称转换为如图所示的等效字符串.任何想法如何?

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?

var = {}
print ???  # Would like to see 'var'
something_else = 3
print ???  # Would print 'something_else'

推荐答案

TL;DR:不可能.见最后的结论".


有一个使用场景,您可能需要它.我并不是暗示没有更好的方法或实现相同的功能.

TL;DR: Not possible. See 'conclusion' at the end.


There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.

这对于在出错、调试模式和其他类似情况下转储"任意字典列表非常有用.

This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.

需要的是 eval() 函数的反向:

What would be needed, is the reverse of the eval() function:

get_indentifier_name_missing_function()

它将一个标识符名称('variable'、'dictionary' 等)作为参数,并返回一个包含标识符名称的字符串.

which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.

考虑以下当前状况:

random_function(argument_data)

如果将标识符名称('function'、'variable'、'dictionary'等)argument_data 传递给 random_function()(另一个标识符名称),实际上将一个标识符(例如:)传递给另一个标识符(例如:):

If one is passing an identifier name ('function','variable','dictionary',etc) argument_data to a random_function() (another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>) to another identifier (e.g.: <function random_function at 0xafff78>):

<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)

根据我的理解,只有内存地址传递给函数:

From my understanding, only the memory address is passed to the function:

<function at 0xafff78>(<object at 0xb1ce10>)

因此,需要将字符串作为参数传递给 random_function() 以便该函数具有参数的标识符名称:

Therefore, one would need to pass a string as an argument to random_function() in order for that function to have the argument's identifier name:

random_function('argument_data')

random_function() 内部

Inside the random_function()

def random_function(first_argument):

,可以使用已经提供的字符串 'argument_data' 来:

, one would use the already supplied string 'argument_data' to:

  1. 用作标识符名称"(用于显示、记录、字符串拆分/连接等)

  1. serve as an 'identifier name' (to display, log, string split/concat, whatever)

馈送 eval() 函数以获得对实际标识符的引用,从而获得对真实数据的引用:

feed the eval() function in order to get a reference to the actual identifier, and therefore, a reference to the real data:

print("Currently working on", first_argument)
some_internal_var = eval(first_argument)
print("here comes the data: " + str(some_internal_var))

不幸的是,这并不适用于所有情况.它仅在 random_function() 可以将 'argument_data' 字符串解析为实际标识符时才有效.IE.如果 argument_data 标识符名称在 random_function() 的命名空间中可用.

Unfortunately, this doesn't work in all cases. It only works if the random_function() can resolve the 'argument_data' string to an actual identifier. I.e. If argument_data identifier name is available in the random_function()'s namespace.

情况并非总是如此:

# main1.py
import some_module1

argument_data = 'my data'

some_module1.random_function('argument_data')


# some_module1.py
def random_function(first_argument):
    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
######

预期结果是:

Currently working on: argument_data
here comes the data: my data

因为 argument_data 标识符名称在 random_function() 的命名空间中不可用,这将改为:

Because argument_data identifier name is not available in the random_function()'s namespace, this would yield instead:

Currently working on argument_data
Traceback (most recent call last):
  File "~/main1.py", line 6, in <module>
    some_module1.random_function('argument_data')
  File "~/some_module1.py", line 4, in random_function
    some_internal_var = eval(first_argument)
  File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined


现在,考虑 get_indentifier_name_missing_function() 的假设用法,它的行为与上述相同.


Now, consider the hypotetical usage of a get_indentifier_name_missing_function() which would behave as described above.

这是一个虚拟的 Python 3.0 代码:.

Here's a dummy Python 3.0 code: .

# main2.py
import some_module2
some_dictionary_1       = { 'definition_1':'text_1',
                            'definition_2':'text_2',
                            'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
                            'key_4':'value_4', 
                            'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
                            'etc':'etc.' }

for each_one_of_my_dictionaries in ( some_dictionary_1,
                                     some_other_dictionary_2,
                                     ...,
                                     some_other_dictionary_n ):
    some_module2.some_function(each_one_of_my_dictionaries)


# some_module2.py
def some_function(a_dictionary_object):
    for _key, _value in a_dictionary_object.items():
        print( get_indentifier_name_missing_function(a_dictionary_object)    +
               "    " +
               str(_key) +
               "  =  " +
               str(_value) )
######

预期结果是:

some_dictionary_1    definition_1  =  text_1
some_dictionary_1    definition_2  =  text_2
some_dictionary_1    etc  =  etc.
some_other_dictionary_2    key_3  =  value_3
some_other_dictionary_2    key_4  =  value_4
some_other_dictionary_2    etc  =  etc.
......
......
......
some_other_dictionary_n    random_n  =  random_n
some_other_dictionary_n    etc  =  etc.

不幸的是,get_indentifier_name_missing_function() 不会看到原始"标识符名称(some_dictionary_,some_other_dictionary_2,some_other_dictionary_n>).它只会看到 a_dictionary_object 标识符名称.

Unfortunately, get_indentifier_name_missing_function() would not see the 'original' identifier names (some_dictionary_,some_other_dictionary_2,some_other_dictionary_n). It would only see the a_dictionary_object identifier name.

因此真正的结果应该是:

Therefore the real result would rather be:

a_dictionary_object    definition_1  =  text_1
a_dictionary_object    definition_2  =  text_2
a_dictionary_object    etc  =  etc.
a_dictionary_object    key_3  =  value_3
a_dictionary_object    key_4  =  value_4
a_dictionary_object    etc  =  etc.
......
......
......
a_dictionary_object    random_n  =  random_n
a_dictionary_object    etc  =  etc.

因此,在这种情况下,eval() 函数的反向操作不会那么有用.

So, the reverse of the eval() function won't be that useful in this case.

目前,人们需要这样做:

Currently, one would need to do this:

# main2.py same as above, except:

    for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
                                               'some_other_dictionary_2',
                                               '...',
                                               'some_other_dictionary_n' ):
        some_module2.some_function( { each_one_of_my_dictionaries_names :
                                     eval(each_one_of_my_dictionaries_names) } )
    
    
    # some_module2.py
    def some_function(a_dictionary_name_object_container):
        for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
            for _key, _value in _dictionary_object.items():
                print( str(_dictionary_name) +
                       "    " +
                       str(_key) +
                       "  =  " +
                       str(_value) )
    ######


总结:

  • Python 仅将内存地址作为参数传递给函数.
  • 表示标识符名称的字符串,如果名称标识符在当前命名空间中可用,则只能通过 eval() 函数引用回实际标识符.
  • eval() 函数的假设反向,在调用代码不能直接看到"标识符名称的情况下没有用.例如.在任何被调用的函数中.
  • 目前需要传递给一个函数:


    In conclusion:

    • Python passes only memory addresses as arguments to functions.
    • Strings representing the name of an identifier, can only be referenced back to the actual identifier by the eval() function if the name identifier is available in the current namespace.
    • A hypothetical reverse of the eval() function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.
    • Currently one needs to pass to a function:

      1. 表示标识符名称的字符串
      2. 实际标识符(内存地址)

    • 这可以通过同时将 'string'eval('string') 传递给被调用函数来实现.我认为这是在不使用极端情况解决方案的情况下跨任意函数、模块、命名空间解决这个蛋鸡问题的最通用"方法.唯一的缺点是使用 eval() 函数可能很容易导致不安全的代码.必须注意不要向 eval() 函数提供任何内容,尤其是未过滤的外部输入数据.

      This can be achieved by passing both the 'string' and eval('string') to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval() function which may easily lead to unsecured code. Care must be taken to not feed the eval() function with just about anything, especially unfiltered external-input data.

      这篇关于将变量名转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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