Convert Variable Name to String?

前端 未结 16 1588
生来不讨喜
生来不讨喜 2020-11-28 04:33

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_         


        
相关标签:
16条回答
  • 2020-11-28 04:54

    By using the the unpacking operator:

    >>> def tostr(**kwargs):
        return kwargs
    
    >>> var = {}
    >>> something_else = 3
    >>> tostr(var = var,something_else=something_else)
    {'var' = {},'something_else'=3}
    
    0 讨论(0)
  • 2020-11-28 04:54

    I don't know it's right or not, but it worked for me

    def varname(variable):
        names = []
        for name in list(globals().keys()):
            string = f'id({name})'
            if id(variable) == eval(string):
                names.append(name)
        return names[0]  
    
    0 讨论(0)
  • 2020-11-28 04:55

    Does Django not do this when generating field names?

    http://docs.djangoproject.com/en/dev//topics/db/models/#verbose-field-names

    Seems reasonable to me.

    0 讨论(0)
  • 2020-11-28 04:56

    Here is a succinct variation that lets you specify any directory. The issue with using directories to find anything is that multiple variables can have the same value. So this code returns a list of possible variables.

    def varname( var, dir=locals()):
      return [ key for key, val in dir.items() if id( val) == id( var)]
    
    0 讨论(0)
  • 2020-11-28 04:56

    You somehow have to refer to the variable you want to print the name of. So it would look like:

    print varname(something_else)
    

    There is no such function, but if there were it would be kind of pointless. You have to type out something_else, so you can as well just type quotes to the left and right of it to print the name as a string:

    print "something_else"
    
    0 讨论(0)
  • 2020-11-28 04:58

    I searched for this question because I wanted a Python program to print assignment statements for some of the variables in the program. For example, it might print "foo = 3, bar = 21, baz = 432". The print function would need the variable names in string form. I could have provided my code with the strings "foo","bar", and "baz", but that felt like repeating myself. After reading the previous answers, I developed the solution below.

    The globals() function behaves like a dict with variable names (in the form of strings) as keys. I wanted to retrieve from globals() the key corresponding to the value of each variable. The method globals().items() returns a list of tuples; in each tuple the first item is the variable name (as a string) and the second is the variable value. My variablename() function searches through that list to find the variable name(s) that corresponds to the value of the variable whose name I need in string form.

    The function itertools.ifilter() does the search by testing each tuple in the globals().items() list with the function lambda x: var is globals()[x[0]]. In that function x is the tuple being tested; x[0] is the variable name (as a string) and x[1] is the value. The lambda function tests whether the value of the tested variable is the same as the value of the variable passed to variablename(). In fact, by using the is operator, the lambda function tests whether the name of the tested variable is bound to the exact same object as the variable passed to variablename(). If so, the tuple passes the test and is returned by ifilter().

    The itertools.ifilter() function actually returns an iterator which doesn't return any results until it is called properly. To get it called properly, I put it inside a list comprehension [tpl[0] for tpl ... globals().items())]. The list comprehension saves only the variable name tpl[0], ignoring the variable value. The list that is created contains one or more names (as strings) that are bound to the value of the variable passed to variablename().

    In the uses of variablename() shown below, the desired string is returned as an element in a list. In many cases, it will be the only item in the list. If another variable name is assigned the same value, however, the list will be longer.

    >>> def variablename(var):
    ...     import itertools
    ...     return [tpl[0] for tpl in 
    ...     itertools.ifilter(lambda x: var is x[1], globals().items())]
    ... 
    >>> var = {}
    >>> variablename(var)
    ['var']
    >>> something_else = 3
    >>> variablename(something_else)
    ['something_else']
    >>> yet_another = 3
    >>> variablename(something_else)
    ['yet_another', 'something_else']
    
    0 讨论(0)
提交回复
热议问题