0

Is it possible to get the name of the variable passed to a function/class as a string? So if would pass the variable into a function I could use the name of variable inside as a string. How to change example function to get the str name:

var_passed = [1,2,3]
def fun(data_):
    print(get_the_var_name_as_string)
fun(var_passed)

so it would give me string:

'var_passed'

My more complex example, where I would like to have the dataframe demo_data used as some_data string variable:

import tkinter as Tk
from pandastable import Table
from demo import demo_data
import pandas as pd


class Result_pandastable(Tk.Frame):
    """Frame for panda dataframe with the pandastable module"""

    def __init__(self, parent=None, dataframe_: pd.DataFrame = None):
        self.parent = parent
        Tk.Frame.__init__(self)
        some_name = 'name'
        self.main = self.master
        self.main.geometry('800x800+200+100')
        self.main.title('Results_'+ some_name)
        self.tk_frame = Tk.Frame(self.main)
        self.tk_frame.pack(fill=Tk.BOTH, expand=1)

        self.df_steps = pd.DataFrame(data=dataframe_)

    def draw_table(self):
        self.table = pt = Table(self.tk_frame, dataframe=self.df_steps, showtoolbar=True, showstatusbar=True, showindex= True)
        pt.show()
        self.pack(fill=Tk.BOTH, expand=1)
        self.mainloop()

def draw_table(dataframe_):
    Result_pandastable(dataframe_= dataframe_).draw_table()

if __name__ == '__main__':
    draw_table(demo_data)
Gerard
  • 117
  • 7

1 Answers1

0

Here's an approach using globals and id:

>>> def fun(data):
...     try:
...         print(next(name for name, val in globals().items() if id(val) == id(data)))
...     except StopIteration:
...         print(f"{data} is nameless!")
...
>>> var_passed = [1, 2, 3]
>>> fun(var_passed)
var_passed
>>> fun([1, 2, 3])
[1, 2, 3] is nameless!
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Only works for global variables. – kindall Nov 02 '21 at 15:35
  • Fun times: `a = 1`, `fun(1)` (the results can differ by Python implementation, but they won't if you replace `1` with `None`). Or similarly, `a = 1`, `b = 0`, `b += 1`, `fun(b)` (which will typically report `a` on modern Python). Basically, never, ever do this (or anything similar involving heuristic stack frame traversal); it's so incredibly inaccurate you'll never get an answer you can actually trust from it. – ShadowRanger Nov 02 '21 at 15:37
  • Side-note: `id(val) == id(data)` is a slow way to spell `val is data`. The two are guaranteed to be equivalent tests, but using `id` involves loading and calling globals, constructing and throwing away new `int`s, etc., where `val is data` is literally a pointer equality test (at least on CPython; it should be equivalently cheap on any implementation though). – ShadowRanger Nov 02 '21 at 15:37
  • @kindall: There are terrible ways to directly inspect the stack frame with the `inspect` module (and maybe the `traceback` module, can't recall if it provides any direct support) to make it "work" heuristically (in the "guessing badly" sense) for non-globals. It's still an awful idea. – ShadowRanger Nov 02 '21 at 15:37