I want to get the names of the variables, that were used to create (a large number of) instances of a certain class.
Therefore, I'm using dir()
to get a list of names in the local scope. After that, I check if one of these names is the name of a variable, that points to an instance of the class Employee
.
I'm aware of the fact, that this might be quite slow, if there is a large number of names in the local scope. But speed is not an issue for me at this point.
So my question is: Would that be considered 'bad practice'? - I'm just curious, because I have the strange feeling, that it is somehow not ok / wrong to do it this way...
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
H1001 = Employee('Tom', 32)
H1002 = Employee('Paula', 28)
for name in dir():
if eval('isinstance({}, Employee)'.format(name)):
print("Instance of the class 'Employee' - variable '{}':".format(name))
print(" The name is {}!".format(eval('{}.name'.format(name))))
print(" {} years old!".format(eval('{}.age'.format(name))))
Output:
Instance of the class 'Employee' - variable 'H1001':
The name is Tom!
32 years old!
Instance of the class 'Employee' - variable 'H1002':
The name is Paula!
28 years old!
Edit: I don't think, that this is a duplicate of this question: How do I create a variable number of variables? - I'm not looking for a way to create variable variables in Python.
Think of it like this: Someone else created the class and a huge number of instances. Imagine that this part of the code can't be changed. - Now my task would be, to find out, how many of these instances have been created and how I could get the name of the variables ('H1001', 'H1002' ... 'H2034'), that have been used during this process.
One possible solution I could think of, was to loop through all the names in the local scope and ask for every name in that list: "Are you the name of a variable, that refers to an instance of the class 'Employee'?" - As you can see in the output, I'm getting the result I was looking for. But it felt 'wrong' to do it this way. So I just wanted some kind of feedback, if this could be a valid solution at all.