Getting the name of a variable as a string

前端 未结 23 2661
旧时难觅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: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() 
    users = Wrapper() 
    queues = Wrapper() 
    priorities = Wrapper() 
    
    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  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 = 
    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.

提交回复
热议问题