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
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:
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).