0

I want to make a function in Python that will print information about a variable given to it elegantly. If I did this for dictionaries, I might command and receive

>> dict1 = {'r':5,'t':3}
>> prettyPrint(dict1)

    dict1 is a dictionary with entries:

     r: 5
     t: 3

But I'm having difficulty finding any straightforward way of extracting the name that an input variable had in the system before it was given to a function.

Some questions have come close to asking what I'm wondering about, but the answers on Variable name to string in Python either make use of not actually needing what I'm asking for or confess to being bad practice.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Post169
  • 668
  • 8
  • 26
  • 1
    Suppose you call `prettyPrint(dict(dict1))`... what should be printed? – kindall Feb 15 '19 at 21:42
  • 3
    An object can be referred to by multiple names, or via containers, or neither of the above (`prettyPrint("this?")`). See also https://stackoverflow.com/q/2749796/3001761, and https://nedbatchelder.com/text/names1.html. – jonrsharpe Feb 15 '19 at 21:43
  • @kindall @jonrsharpe Matlab, which has the functionality I'm trying to mimic, refers to values that are not individual variables as `ans` – Post169 Feb 15 '19 at 21:48
  • 1
    Maybe this can answer to your question : [Get the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string/18425523) – Florian Toqué Feb 15 '19 at 21:49
  • 2
    In Python, `dict1` is just a name that is bound to a `dict` value; there is no concrete "variable" object that has both the name `"dict1"` and the corresponding `dict` instance as attributes. `prettyPrint` gets the `dict` only, not any information about the name it was bound to. The only equivalent in Python would be to call `prettyPrint({'dict1': dict1})` explicitly, and have `prettyPrint` use the key and the value from its argument. – chepner Feb 15 '19 at 21:50

1 Answers1

0

In Python, function objects have a .func_name attribute. So you might try that.

Below there is a solution that is very hacky but could work for things other than functions -- maybe it will be useful too?

So, one idea (although it isn't smart about cases where variables have multiple names, and it also won't work on expressions that are not variables, and also it should not be thought of as "fast") is as follows:

from itertools import chain

def variable_name(variable):
    for name, object in chain(globals().items(), locals().items()):
        if object is variable:
            return name
    return None # didn't find anything...

This accepts anything, not just functions, and looks through the global and local symbol tables to see if what you're looking for is there.

Since you're also printing type info, you might like to check out the type builtin function, which will give you that info.

mostsquares
  • 834
  • 8
  • 27