Getting the name of a variable as a string

前端 未结 23 2656
旧时难觅i
旧时难觅i 2020-11-22 00:19

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string?

How can I do the same for a variable? As oppose

相关标签:
23条回答
  • 2020-11-22 00:47
    >> my_var = 5
    >> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
    >> my_var_name 
    'my_var'
    

    locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

    from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

    0 讨论(0)
  • 2020-11-22 00:48

    With Python 3.8 one can simply use f-string debugging feature:

    >>> foo = dict()
    >>> f'{foo=}'.split('=')[0]
    'foo' 
    
    0 讨论(0)
  • 2020-11-22 00:49

    On python3, this function will get the outer most name in the stack:

    import inspect
    
    
    def retrieve_name(var):
            """
            Gets the name of var. Does it from the out most frame inner-wards.
            :param var: variable to get name from.
            :return: string
            """
            for fi in reversed(inspect.stack()):
                names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
                if len(names) > 0:
                    return names[0]
    

    It is useful anywhere on the code. Traverses the reversed stack looking for the first match.

    0 讨论(0)
  • 2020-11-22 00:52

    Using the python-varname package, you can easily retrieve the name of the variables

    https://github.com/pwwang/python-varname

    In your case, you can do:

    from varname import Wrapper
    
    foo = Wrapper(dict())
    
    # foo.name == 'foo'
    # foo.value == {}
    foo.value['bar'] = 2
    

    For list comprehension part, you can do:

    n_jobs = Wrapper(<original_value>) 
    users = Wrapper(<original_value>) 
    queues = Wrapper(<original_value>) 
    priorities = Wrapper(<original_value>) 
    
    list_of_dicts = [n_jobs, users, queues, priorities]
    columns = [d.name for d in list_of_dicts]
    # ['n_jobs', 'users', 'queues', 'priorities']
    # REMEMBER that you have to access the <original_value> by d.value
    

    You can also try to retrieve the variable name DIRECTLY:

    from varname import nameof
    
    foo = dict()
    
    fooname = nameof(foo)
    # fooname == 'foo'
    

    Note that this is working in this case as you expected:

    n_jobs = <original_value>
    d = n_jobs
    
    nameof(d) # will return d, instead of n_jobs
    # nameof only works directly with the variable
    

    I am the author of this package. Please let me know if you have any questions or you can submit issues on Github.

    0 讨论(0)
  • 2020-11-22 00:52

    I don't believe this is possible. Consider the following example:

    >>> a = []
    >>> b = a
    >>> id(a)
    140031712435664
    >>> id(b)
    140031712435664
    

    The a and b point to the same object, but the object can't know what variables point to it.

    0 讨论(0)
  • 2020-11-22 00:52
    >>> locals()['foo']
    {}
    >>> globals()['foo']
    {}
    

    If you wanted to write your own function, it could be done such that you could check for a variable defined in locals then check globals. If nothing is found you could compare on id() to see if the variable points to the same location in memory.

    If your variable is in a class, you could use className.dict.keys() or vars(self) to see if your variable has been defined.

    0 讨论(0)
提交回复
热议问题