'Python instances should be created at the beginning or create them as we need them? [closed]

If we talk about resources, memory, legibility what would be better between:

  1. Create all the instances at the beginning of a method? (left side of the screenshot)

  2. Create the instances as we need to use them? (right side of the screenshot)

Do you have any documentation that says which is better? I searched in the Python documentation but found nothing.

screenshot of two code panes in VSCode



Solution 1:[1]

Well in python creating instances is creating instances, regardless of where you do such, the same amount of instances will be created taking the same amount of storage space.

If you're looking into memory conservation I'd recommend using the del operator when instances are no longer needed.

Other than that this is totally just up to personal preference, and how you'd like to format your code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kunosyn