Python Forum
Printing the variable from defined function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing the variable from defined function
#1
Hi,

Quite new topython and this is a problem I have spent 1.5 hrs trying to work out, for context I wanted to define a function that would create a file named based on the variable input to the function. I have come across the issue that I am able to return the variable's value or the function define, but am not able to print the variable I am putting into the function.

I have given a brief example of what I mean- I would want the function to print 'a' if "function(a)" is ran. Thanks in advance, I'm sure there is a easy solution but searching forums/google has not got me beyond the .split('=')

a = 3

def function (input):
    print(f"{input}")
    print(f"{input=}".split('=')[0])

function(a)
Reply
#2
Avoid using the names of built-in functions (input) or classes as variable names. Here it does no harm, but it is a bad habit and it easily leads to confusion. Or maybe it already has?

I'm having trouble understanding your question. The code does exactly what I would expect, so looking at the code doesn't help much. Which of the prints doesn't work as you expect? The one that prints "3", the value of "a", or the one that prints "input", the first string returned by split("="). Maybe you should post what you want for output.

Do you want your function to print the letter "a" because it is the variable passed to the function? If so, why? Like so many things, this is possible, but of what use is it? Here is some code that retrieves the python expression that called function, and extracts the argument variable name from that line.
import traceback
import re

a = 3
 
def function (arg):
    stack = traceback.extract_stack()
    print(re.search("\((.*)\)", stack[-2].line).group(1), "=", arg)
 
function(a)
Output:
a = 3
That was fun to write, but I cannot see any use for such a thing. It certainly would be of no use in a filename generator function.
Reply
#3
Clarifying - it prints the _value_ of a, as Dean H points out. Did you want it to print the name "a" instead?
Reply
#4
(Sep-02-2023, 07:42 PM)jefsummers Wrote: Clarifying - it prints the _value_ of a, as Dean H points out. Did you want it to print the name "a" instead?

Yes, sorry my explanation was not very clear- you are right that I was looking for it to print "a". This is so that if I am entering a dataframe, "a", into a function for graphing, the output file has the source dataframe in the file name so that I know which dataset it was built from.
Reply
#5
(Sep-02-2023, 07:24 PM)deanhystad Wrote: Avoid using the names of built-in functions (input) or classes as variable names. Here it does no harm, but it is a bad habit and it easily leads to confusion. Or maybe it already has?

I'm having trouble understanding your question. The code does exactly what I would expect, so looking at the code doesn't help much. Which of the prints doesn't work as you expect? The one that prints "3", the value of "a", or the one that prints "input", the first string returned by split("="). Maybe you should post what you want for output.

Do you want your function to print the letter "a" because it is the variable passed to the function? If so, why? Like so many things, this is possible, but of what use is it? Here is some code that retrieves the python expression that called function, and extracts the argument variable name from that line.
import traceback
import re

a = 3
 
def function (arg):
    stack = traceback.extract_stack()
    print(re.search("\((.*)\)", stack[-2].line).group(1), "=", arg)
 
function(a)
Output:
a = 3
That was fun to write, but I cannot see any use for such a thing. It certainly would be of no use in a filename generator function.

Sorry, yes, the context for this would be so that I can generate plots and name them based on the name of the dataframe used to create- here, "a" would be the df containing the information. So I would be outputting a file "time_plot_a.png" for example.
Reply
#6
That is an odd thing to do, and I strongly advise against it. Functions should only care about the values passed, not about the name of some variable that once referenced the value. That is why you could find no information about it.

If you want your dataframes to have a name, give them a name.
df = pandas.DataFrame(...)
df.name = "some name I want associated with this dataframe"
Your "time_plot_a" dataframe might be reference by several variables at different times during its lifetime. Which one should give it a name? You are saying the only important variable is the one that was used to call the function that saves a plot? Making a plot and saving the plot to a file sounds like a useful thing. Something I would want to use over and over. By naming the file after the variable used to reference the dataframe in the function call you have placed severe restrictions on how this function can be used.

Personally, I don't think you should name the file. I would pop up a dialog asking for the user to select/enter a filename, and a file type.
Reply
#7
(Sep-02-2023, 10:14 PM)deanhystad Wrote: That is an odd thing to do, and I strongly advise against it. Functions should only care about the values passed, not about the name of some variable that once referenced the value. That is why you could find no information about it.

If you want your dataframes to have a name, give them a name.
df = pandas.DataFrame(...)
df.name = "some name I want associated with this dataframe"
Your "time_plot_a" dataframe might be reference by several variables at different times during its lifetime. Which one should give it a name? You are saying the only important variable is the one that was used to call the function that saves a plot? Making a plot and saving the plot to a file sounds like a useful thing. Something I would want to use over and over. By naming the file after the variable used to reference the dataframe in the function call you have placed severe restrictions on how this function can be used.

Personally, I don't think you should name the file. I would pop up a dialog asking for the user to select/enter a filename, and a file type.

This is a much better method, thank you so much for this- I wasn't aware of the ability to name a df like this.
Reply
#8
Adding attributes is something you can do with most python objects.

In python everything is an object. Each object is an instance of a class. The class defines what methods (functions) the object can execute, and the __init__() method assigns attributes. But the __init__() method is just a convenience. When you assign a value to an attribute in the __init__() method, you are adding a key/value pair to a dictionary, __dict__. You can add attributes to the object at any time, from anywhere, and they are added to the __dict__. That is all I did in my example. I added a "name" attribute to a DataFrame object's __dict__. The DataFrame class is completely unaware of the new attribute.

Not all objects support adding attributes. Some python classes use __slots__ instead of __dict__. Slots objects use less memory and they are faster than objects that use __dict__, but they are less flexible because their attributes are set by the class (the attribute names, not the values). And some python classes that use __dict__ disable the mechanism that lets you add attributes to an object. But these are in the minority, and most python objects let you add whatever attributes you want whenever you want.
class MostlyEmptyClass:
    def __init__(self):
        self.a = 1

x = MostlyEmptyClass()
print(x.__dict__)
x.b = 2
print(x.__dict__)
Output:
{'a': 1} {'a': 1, 'b': 2}
When adding attributes this way it is wise to first print the dir() to verify you are not stomping all over an existing instance variable OR METHOD. Reading the documentation does not tell you everything about a class.
Output:
>>> dir(x) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 3 298 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  Variable for the value element in the index function?? Learner1 8 667 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 602 Nov-23-2023, 02:53 PM
Last Post: rob101
  Function parameter not writing to variable Karp 5 951 Aug-07-2023, 05:58 PM
Last Post: Karp
  Getting NameError for a function that is defined JonWayn 2 1,122 Dec-11-2022, 01:53 PM
Last Post: JonWayn
Question Help with function - encryption - messages - NameError: name 'message' is not defined MrKnd94 4 2,912 Nov-11-2022, 09:03 PM
Last Post: deanhystad
  How to print the output of a defined function bshoushtarian 4 1,321 Sep-08-2022, 01:44 PM
Last Post: deanhystad
  Retrieve variable from function labgoggles 2 1,056 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  User-defined function to reset variables? Mark17 3 1,660 May-25-2022, 07:22 PM
Last Post: Gribouillis
  [variable] is not defined error arises despite variable being defined TheTypicalDoge 4 2,146 Apr-05-2022, 04:55 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020