0

I am currently working on building a piece of code that is composing business objects from tuples that it has been given by the data source I am using. Since these tuples may vary in length and their naming, I want to insert a pre-defined tuple into the for loop.

class_attributes = ("_id", "_first_name", "_last_name")
for class_attributes in answer:
        # I would want to access them dynamically in here, instead Python is using "class_attributes" as a local variable inside the for loop

The piece of code from above usually fetches the tuple dynamically, resulting in different arguments and lengths of the tuple, therefore copying the line of code into the for loop is not feasible.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Fynn Mehrens
  • 3
  • 1
  • 2
  • yeah, u can feth each item dynamically – Ghost Ops Sep 20 '21 at 11:39
  • How do you intend to use the tuple? What is the end result? – Mohammad Sep 20 '21 at 11:42
  • try `for i in range(len(class_attributes)): print(class_attributes[i])` – Ghost Ops Sep 20 '21 at 11:43
  • @Mohammad In the place where I would normally include "for (id, first_name, last_name) in answer:", I want to insert a tuple dynamically, so that I am not bound to those attributes. – Fynn Mehrens Sep 20 '21 at 11:45
  • 1
    @FynnMehrens The best solution I could think of is using default dict instead of tuples. What you are trying to do might be possible but is not very recommended. Instead, using dicts is the way to go when you have an unknown number of variables. – Mohammad Sep 20 '21 at 12:00
  • 1
    @FynnMehrens A much better approach would be to wrap the tuples in an [adapter class](https://en.wikipedia.org/wiki/Adapter_pattern) so that the fields can be accessed using a common interface (i.e. with any missing fields returning appropriate default values). – ekhumoro Sep 20 '21 at 12:12
  • Not sure if I completely understand, but maybe [namedtuples](https://docs.python.org/3.9/library/collections.html?highlight=namedtuple#collections.namedtuple) are an alternative (defaults are possible)? – Timus Sep 20 '21 at 13:01

1 Answers1

-1

The for loop you show loops over the elemments in answer and assigns them to a variable named class_attributes, overwriting the previous assignment of the list of attributes to that variable.

If you don't mean this, I don't understand the question

>>> answers = [(1,'Guido', 'van Rossum'), (2, 'Tim', 'Peters')]
>>> for _id, _first_name, _last_name in answers:
...     print(_id, _first_name, _last_name)
...
1 Guido van Rossum
2 Tim Peters