Simpler way to create dictionary of separate variables?

前端 未结 27 1891
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
相关标签:
27条回答
  • 2020-11-22 03:17

    you can use easydict

    >>> from easydict import EasyDict as edict
    >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
    >>> d.foo
    3
    >>> d.bar.x
    1
    >>> d = edict(foo=3)
    >>> d.foo
    3
    

    another example:

    >>> d = EasyDict(log=False)
    >>> d.debug = True
    >>> d.items()
    [('debug', True), ('log', False)]
    
    0 讨论(0)
  • 2020-11-22 03:17

    It will not return the name of variable but you can create dictionary from global variable easily.

    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}
    
    0 讨论(0)
  • 2020-11-22 03:18

    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 03:19

    While this is probably an awful idea, it is along the same lines as rlotun's answer but it'll return the correct result more often.

    import inspect
    def getVarName(getvar):
      frame = inspect.currentframe()
      callerLocals = frame.f_back.f_locals
      for k, v in list(callerLocals.items()):
        if v is getvar():
          callerLocals.pop(k)
          try:
            getvar()
            callerLocals[k] = v
          except NameError:
            callerLocals[k] = v
            del frame
            return k
      del frame
    

    You call it like this:

    bar = True
    foo = False
    bean = False
    fooName = getVarName(lambda: foo)
    print(fooName) # prints "foo"
    
    0 讨论(0)
  • 2020-11-22 03:21
    import re
    import traceback
    
    pattren = re.compile(r'[\W+\w+]*get_variable_name\((\w+)\)')
    def get_variable_name(x):
        return pattren.match( traceback.extract_stack(limit=2)[0][3]) .group(1)
    
    a = 1
    b = a
    c = b
    print get_variable_name(a)
    print get_variable_name(b)
    print get_variable_name(c)
    
    0 讨论(0)
  • 2020-11-22 03:23
    >>> a = 1
    >>> b = 1
    >>> id(a)
    34120408
    >>> id(b)
    34120408
    >>> a is b
    True
    >>> id(a) == id(b)
    True
    

    this way get varname for a maybe 'a' or 'b'.

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