I'm iterating through and want to save generator objects as I go along.
In the example below, I want the variable "gen" (the generator returned) to return "Tom" and "Tommy", but I find that when I mutate the original list the generator was called on, it also changes my generator object.
Desired behavior would be to save these generator objects as I go along, without having them being modified.
I understand that a list is mutable, but if this was run with a function, it would save the output to the variable, and that output could NOT be changed.
(for more context, I'm building a dictionary of generators where point-in-time matters, I chose a generator because the computation is pretty heavy and want to save it until the end)
# simple class
class Name:
def __init__(self, name):
self.name = name
# simple generator
def generator_function(lst):
for obj in lst:
yield obj.name
lst = [Name("Tom"), Name("Tommy")]
# create gen object
gen= generator_function(lst)
# mutate list
lst[0] = Name("Andrea")
# >>> Prints out : "Andrea" , "Tommy"
# >>> Desired output: "Tom", "Tommy"
for ii in gen:
print(ii)
As you said yourself, python lists are variable. Therefore, you will have to make a new copy for every generator you create.
This can be achieved easily by modifying your call to generator_function
:
gen = generator_function(list(lst))
I'm not personally crazy about hoping the user remembers to copy their list when passing to the generator. In this case, you can return a generator expression:
from typing import List, Iterable
def generator_function(lst: List[Name]) -> Iterable[str]:
return (obj.name for obj in lst.copy())
I've also added annotations since I think it's important, especially here where your generator is accessing a .name
property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.