Simpler way to create dictionary of separate variables?

前端 未结 27 1915
名媛妹妹
名媛妹妹 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:14

    Most objects don't have a __name__ attribute. (Classes, functions, and modules do; any more builtin types that have one?)

    What else would you expect for print(my_var.__name__) other than print("my_var")? Can you simply use the string directly?

    You could "slice" a dict:

    def dict_slice(D, keys, default=None):
      return dict((k, D.get(k, default)) for k in keys)
    
    print dict_slice(locals(), ["foo", "bar"])
    # or use set literal syntax if you have a recent enough version:
    print dict_slice(locals(), {"foo", "bar"})
    

    Alternatively:

    throw = object()  # sentinel
    def dict_slice(D, keys, default=throw):
      def get(k):
        v = D.get(k, throw)
        if v is not throw:
          return v
        if default is throw:
          raise KeyError(k)
        return default
      return dict((k, get(k)) for k in keys)
    

提交回复
热议问题