27 Oct 2022

Python Tip: Get Variable Name in Python (type of reflection?)

收藏到CSDN网摘




Sometimes, you may want to get the variable name itself as a string while writing Python code. For instance, if you are going to write 'a = 2', is there a convenient way of getting the variable name '"a"' by calling a function using 'a' as the parameter? The short answer is YES. It's completely possible in Python! By it's a little bit tricky to do so. Generally, it can be done by using the following one line of code - the lambda function!
ff = lambda **k: list(k.keys())[0]
However, when you try to call it, it has to be called in the following way.
ff = lambda **k: list(k.keys())[0]
var = 10
ff(var=var)

No comments :

Post a Comment