• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

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

Red Squirrel

No Lifer
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.
 
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.
 
Back
Top