-2
class source():
    def __init(self, _source: object):
        self.source = _source

    def __str__(self):
        return (f"source: {self.source}")

value0 = 10
value1 = source(value0)
print(value1)

This will print out "source: 10".

However i want it to print out "source: value0", because if i want to change value0 to 15 it will return a different string. Its also for readability, it will make it more clear where the value is coming from.

How do i get the name of a float (or int) type variable?

poendie
  • 15
  • 4
  • 1
    TL;DR: you can't, and it makes no sense. – deceze May 17 '22 at 11:00
  • 1
    The variable is not the argument: only the value it holds. – khelwood May 17 '22 at 11:01
  • 1
    inside the method `source.__str__()` it has no knowledge or access to `value0` (or `value1` for that matter), since it's not within the scope, so what you are trying to do is absolutely impossible, unless you create a type that has some kind of intended label annotated to it. For additional background [this answer (and the associated thread)](https://stackoverflow.com/a/58451182) may be of use. – metatoaster May 17 '22 at 11:01
  • what you can do is make a dictionary, so you pass something like `source({'value0': 10})`. Then inside the source you can process either the name of the variable or the value – Sembei Norimaki May 17 '22 at 11:02
  • Your variable is `self.source`, so why do you want its name to be `value0` instead of `source`? – Mechanic Pig May 17 '22 at 11:23
  • What are you trying to accomplish here that prompted this question? – deceze May 17 '22 at 11:38
  • because i want to see were it gets it data from – poendie May 18 '22 at 10:28
  • You do that with a debugger and tracing the program flow. If "`value0`" is data that's needed for your program to work, then you need to explicitly pass the string `"value0"` to your object, and not rely on implicit variable names. – deceze May 18 '22 at 10:31

0 Answers0