# How to return a variable name and value from within a self-contained function block?

Abstract: I have viewed other solutions on StackExchange but none actually address using a fully self-contained function to return name and value of a variable. The only function that works requires using SetAttributes[...] outside the function before using it: Display variable name instead of value

Goal: to create a completely self-contained function Block[...] or Module[...] that returns variable name and value without requiring using an outside function such as SetAttributes[...].

About the Code: Below is the code for four different attempts. The top two are globally scoped and work fine. Bottom two are written into a function block but do not work. The output is decorated with strings to give you an idea of how I intend to use it.

varname=123;

(* this works *)
Row[{"Global Scope Defer: ","the name is ",Defer@varname," and value is -> ",varname}]

(*this works *)
SetAttributes[ShowName,HoldAll];
ShowName[name_]:=Row[{"Global Scope SetAttributes HoldForm: ","the name is ",HoldForm@name," and value is -> ",ReleaseHold@name}];
ShowName[varname]

(* this doesn't work *)
showDeferFunction[var_]:=Block[{pre,arrow},
pre="the name is ";
arrow=" and value is -> ";
Row[{"Functional Scoping Defer: ",pre,Defer@var,arrow,var}]
];
showDeferFunction[varname]

(* this doesn't work either *)
showHoldFormFunction[var_]:=Block[{pre,arrow},
pre="the name is ";
arrow=" and value is -> ";
SetAttributes[ShowName,HoldAll];
ShowName[name_]:=Row[{"Functional Scoping SetAttributes HoldForm: "pre,HoldForm@name,arrow,ReleaseHold@name}];
ShowName[var]
];
showHoldFormFunction[varname]


The Output:

Global Scope Defer: the name is varname and value is -> 123
Global Scope SetAttributes HoldForm: the name is varname and value is -> 123
Functional Scoping Defer: the name is 123 and value is -> 123
Functional Scoping SetAttributes HoldForm: the name is 123 and value is -> 123

• Something like xxx = 1; Function[Null, Row[{Defer[#1], " = ", #1}], {HoldAll}][xxx]? – J. M.'s ennui May 23 '20 at 7:13
• @J.M. thank you that is close but I am looking for a named function that would look something like below (example doesn't work) so i could re-use it without having to copy the function body each time: fn[var_] := Function[Null, Row[{Defer[#1], " = ", #1}], {HoldAll}][var]; – Jules Manson May 23 '20 at 7:24
• You don't need var; fn = Function[(* stuff *)] suffices. – J. M.'s ennui May 23 '20 at 9:15