If you are trying to iterate over a collection of objects, it's imperative that you separate the name from the object. This is a pretty common pitfall, we give values names (which we call variables) and so the assumption is made that this is the only way to access them.
However, it's best to ignore the names in this case. If you have a bunch of objects that you need access to, just put those objects in a container: list
, set
, tuple
, dict
, etc.
If the name matters to you more than order, then a dict
might be the way to go:
db1, db2, db3 = 1, 2, 3
db_dict = {'db1': db1, 'db2': db2, 'db3': db3}
for name, obj in db_dict.items():
print(name, obj)
db1 1
db2 2
db3 3
Otherwise, what happens if you add a new name (variable)? Say I want db4
now. Well, I need to go in and make a code change. This becomes very fragile and difficult to extend. While you could use exec
or globals()
or locals()
, this is generally regarded as an anti-pattern because you don't really need the names, you need the values themselves, and a consistent way to access them.