Reusing Variables in Python

In Python, I often use variables just like this:

files = files[:batch_size]

I like this technique because it helps me reduce the number of variables that I need to track.

There have never been any problems, but I wonder if I miss the potential flaws, for example. performance etc.

+5
source share
4 answers

There are no technical flaws for reusing variable names. However, if you reuse the variable and change its "target", this may confuse others reading your code (especially if they skip reassignment).

, . GC , ( , ). , batch_size - , , , del files[batch_size:].

+6

: , , , :

import itertools
files = itertools.islice(files, batch_size)

: , ( , / ). -:

Python 2.7.2 (default, Nov 21 2011, 17:25:27) 
[GCC 4.6.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> def func1(files):
...   files = files[:100]
... 
>>> def func2(files):
...   new_files = files[:100]
... 
>>> dis.dis(func1)
  2           0 LOAD_FAST                0 (files)
              3 LOAD_CONST               1 (100)
              6 SLICE+2             
              7 STORE_FAST               0 (files)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE        
>>> dis.dis(func2)
  2           0 LOAD_FAST                0 (files)
              3 LOAD_CONST               1 (100)
              6 SLICE+2             
              7 STORE_FAST               1 (new_files)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE        

Python 3.

, func1 , files .

+5

, , . Python GC , , , C, , .

In addition, you can really confuse future readers of your code, who usually expect new objects to have new names (a byproduct from garbage-collected languages).

+1
source

The downside is that you cannot use:

file_rest = files[batch_size:]

Regarding performance, there are no flaws. On the contrary: you can even improve performance by avoiding the collision of hashes in the same namespace.

In this context, there was an SO-post regarding this.

+1
source

All Articles