1

Trivial example:

a = 1
b = 2
c = 3
rrr = []
rrr.append(a)
rrr.append(b)
rrr.append(c)
rrr

returns:

[1,2,3]

But I need to get:

[a,b,c]

I've seen this:

How can I get the name of an object in Python?

But I'm not quite sure if the solution is saying only functions have a __name__ attribute.

The problem I'm trying to solve is I have a class, and one of its attributes is a list of other attributes it has, so I can iterate through them easily (they all go together very frequently and they're all booleans). But I need to do a check against that list that grabs its name, not its value.

Shouldn't the list point to the variable first and then the value that the variable is referencing, or does python in this instance just skip the little post-it notes that are the variables and just look at the actual objects?

If so, is there anyway to force it, during the construction of the list, to go the long route and look at the post-it note variables so I can recover them?

CapnShanty
  • 529
  • 8
  • 20
  • 4
    Why would you need this? If you want to store names, why not just add strings to the list, or store the associated names and numbers in a dictionary? – Carcigenicate Aug 14 '19 at 20:02
  • I suppose it probably does make more sense to just make a dictionary of these things instead of making them each an attribute, but I'm laaaazy and already did it this way :P (I'll probably just go make it a dictionary) – CapnShanty Aug 14 '19 at 20:06
  • This just seemed to be steering toward "dynamic variables", and in most cases, just using a dictionary will end up being easier in the longer run even if it requires some initial setup. – Carcigenicate Aug 14 '19 at 20:09
  • Even the `__name__` attribute is a side effect of the `def` statement that creates it. It does not directly refer to any one name that references the object. – chepner Aug 14 '19 at 20:24
  • 1
    "Shouldn't the list point to the variable first ..." No; that's not how Python works. Read https://nedbatchelder.com/text/names.html. – chepner Aug 14 '19 at 20:26

1 Answers1

0

you can try:

class MyIntValue:
    def __init__(self, x:int, name:str):
        self.name = name
        self.value = x

    def __repr__(self):
        return self.name


a = MyIntValue(1, 'a')
b = MyIntValue(2, 'b')
c = MyIntValue(3, 'c')
rrr = []
rrr.append(a)
rrr.append(b)
rrr.append(c)

print(rrr)

output:

[a, b, c] 
kederrac
  • 16,819
  • 6
  • 32
  • 55