Getting the name of a variable as a string

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

    In Python, the def and class keywords will bind a specific name to the object they define (function or class). Similarly, modules are given a name by virtue of being called something specific in the filesystem. In all three cases, there's an obvious way to assign a "canonical" name to the object in question.

    However, for other kinds of objects, such a canonical name may simply not exist. For example, consider the elements of a list. The elements in the list are not individually named, and it is entirely possible that the only way to refer to them in a program is by using list indices on the containing list. If such a list of objects was passed into your function, you could not possibly assign meaningful identifiers to the values.

    Python doesn't save the name on the left hand side of an assignment into the assigned object because:

    1. It would require figuring out which name was "canonical" among multiple conflicting objects,
    2. It would make no sense for objects which are never assigned to an explicit variable name,
    3. It would be extremely inefficient,
    4. Literally no other language in existence does that.

    So, for example, functions defined using lambda will always have the "name" , rather than a specific function name.

    The best approach would be simply to ask the caller to pass in an (optional) list of names. If typing the '...','...' is too cumbersome, you could accept e.g. a single string containing a comma-separated list of names (like namedtuple does).

提交回复
热议问题