1

Looking at this Difference between list(numpy_array) and numpy_array.tolist() got me interested in this question. While I don't think that calling list on a numpy array is necessarily a problem, it is often not what I would prefer compared to using the np.ndarray.tolist method.

Just using something like grep for list would return far too many results in some projects. But for some input x it is difficult for me to think of any generally-applicable regex for it.

So instead I am wondering if there is some other way to search the code for calling a list on a numpy array. My best guess is to use the ast library, but I am not familiar with it.

Ideally I would like some kind of function.

import ast


def is_list_on_arr(code):
    '''Indicate if list called on numpy array.'''
    ...

if __name__ == "__main__":
    code = """
    import numpy as np
    arr = np.array([1, 2, 3])
    lst = list(arr)
    """
    is_list_on_arr(code)

How can I check if a code base contains such a pattern?

Galen
  • 1,128
  • 1
  • 14
  • 31
  • 1
    Unless your IDE has a check for this, I don't think it will be easy to do. Figuring out data flow and the types of parameters is complex. – Barmar Apr 26 '23 at 18:03
  • 1
    Unless you were in the habit of using `list` like this, you probably won't find many cases. More likely you might have hidden instances, such as list comprehension, `[i for i in an_array]` or the equivalent `for loop`. – hpaulj Apr 26 '23 at 21:14

0 Answers0