In Python, I often reuse variables in manner analogous to this:
files = files[:batch_size]
I like this technique because it helps me cut on the number of variables I need to track.
Never had any problems but I am wondering if I am missing potential downsides e.g. performance etc.
In Python, we may reuse the same variable to store values of any type. A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old.
It is better to reuse variables in terms of memory. But be careful you don't need the value in a variable before reusing it. Other than that, you shouldn't use always the variable. It is important to keep a clean and readable code.
Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes. Save this answer.
There is no technical downside to reusing variable names. However, if you reuse a variable and change its "purpose", that may confuse others reading your code (especially if they miss the reassignment).
In the example you've provided, though, realize that you are actually spawning an entirely new list when you splice. Until the GC collects the old copy of that list, that list will be stored in memory twice (except what you spliced out). An alternative is to iterate over that list and stop when you reach the batch_size
th element, instead of finishing the list, or even more succinctly, del files[batch_size:]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With