Getting the name of a variable as a string

前端 未结 23 2655
旧时难觅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

    You can try the following to retrieve the name of a function you defined (does not work for built-in functions though):

    import re
    def retrieve_name(func):
        return re.match("<function\s+(\w+)\s+at.*", str(func)).group(1)
    
    def foo(x):
        return x**2
    
    print(retrieve_name(foo))
    # foo
    
    0 讨论(0)
  • 2020-11-22 00:53

    I wrote the package sorcery to do this kind of magic robustly. You can write:

    from sorcery import dict_of
    
    columns = dict_of(n_jobs, users, queues, priorities)
    

    and pass that to the dataframe constructor. It's equivalent to:

    columns = dict(n_jobs=n_jobs, users=users, queues=queues, priorities=priorities)
    
    0 讨论(0)
  • 2020-11-22 00:55
    def name(**variables):
        return [x for x in variables]
    

    It's used like this:

    name(variable=variable)
    
    0 讨论(0)
  • 2020-11-22 00:56

    The only objects in Python that have canonical names are modules, functions, and classes, and of course there is no guarantee that this canonical name has any meaning in any namespace after the function or class has been defined or the module imported. These names can also be modified after the objects are created so they may not always be particularly trustworthy.

    What you want to do is not possible without recursively walking the tree of named objects; a name is a one-way reference to an object. A common or garden-variety Python object contains no references to its names. Imagine if every integer, every dict, every list, every Boolean needed to maintain a list of strings that represented names that referred to it! It would be an implementation nightmare, with little benefit to the programmer.

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

    I have a method, and while not the most efficient...it works! (and it doesn't involve any fancy modules).

    Basically it compares your Variable's ID to globals() Variables' IDs, then returns the match's name.

    def getVariableName(variable, globalVariables=globals().copy()):
        """ Get Variable Name as String by comparing its ID to globals() Variables' IDs
    
            args:
                variable(var): Variable to find name for (Obviously this variable has to exist)
    
            kwargs:
                globalVariables(dict): Copy of the globals() dict (Adding to Kwargs allows this function to work properly when imported from another .py)
        """
        for globalVariable in globalVariables:
            if id(variable) == id(globalVariables[globalVariable]): # If our Variable's ID matches this Global Variable's ID...
                return globalVariable # Return its name from the Globals() dict
    
    0 讨论(0)
  • 2020-11-22 00:57

    Following method will not return the name of variable but using this method you can create data frame easily if variable is available in global scope.

    class CustomDict(dict):
        def __add__(self, other):
            return CustomDict({**self, **other})
    
    class GlobalBase(type):
        def __getattr__(cls, key):
            return CustomDict({key: globals()[key]})
    
        def __getitem__(cls, keys):
            return CustomDict({key: globals()[key] for key in keys})
    
    class G(metaclass=GlobalBase):
        pass
    
    x, y, z = 0, 1, 2
    
    print('method 1:', G['x', 'y', 'z']) # Outcome: method 1: {'x': 0, 'y': 1, 'z': 2}
    print('method 2:', G.x + G.y + G.z) # Outcome: method 2: {'x': 0, 'y': 1, 'z': 2}
    
    A = [0, 1]
    B = [1, 2]
    pd.DataFrame(G.A + G.B) # It will return a data frame with A and B columns
    
    0 讨论(0)
提交回复
热议问题