python temporary class instances, should I copy them when inserting to an array?

Red Squirrel

No Lifer
May 24, 2003
71,316
14,086
126
www.anyf.ca
Say I have code like this:

Code:
	almentries = [];

	files = os.listdir(path)

	for f in files:
		tmpentry = AlmEntry(f);
		
		if tmpentry.Load() :
			print("valid load");
			almentries.append(tmpentry);
		else:
			print("invalid load");

I am declaring a new AlmEntry class instance and assigning it to tmpentry in the loop. I do some validation on it and then I insert it into an array.

Is this valid, or should I actually be using a copy or deepcopy? The code works as I intend the way it is now, but I am just wondering if I might see problems doing it this way or if this is right.
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
This is fine. No need to copy

Every time the loop repeats, tmpentry is getting a new reference assigned to it. That does not changes the values previously stored in the loop.

Because Python is also garbage collected, there's no issue with memory allocation or anything else around tmpentry. This might be a problem in manually managed languages (like C/C++). It's not here.